Why is the performance of HttpClient low?
Here is my test code, accessing a locally running web api program one thousand times took about 31 seconds. and if i use a socket for access, it only takes 0.3 seconds.
var httpclient = new HttpClient();
var ret = await httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack");
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
ret = await httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack");
}
sw.Stop();
var ms = sw.ElapsedMilliseconds;
Tagging subscribers to this area: @dotnet/ncl See info in area-owners.md if you want to be subscribed.
Issue Details
Here is my test code, accessing a locally running web api program one thousand times took about 31 seconds. and if i use a socket for access, it only takes 0.3 seconds.
` var httpclient = new HttpClient(); var ret = await httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack");
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
ret = await httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack");
}
sw.Stop();
var ms = sw.ElapsedMilliseconds;
`
| Author: | simpleway2016 |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | - |
HttpClient will fetch the whole response message and parse it into headers and body.
You may want to parallelize your access:
var httpclient = new HttpClient();
var ret = await httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack");
Stopwatch sw = new Stopwatch();
sw.Start();
var rets = await Task.WhenAll(Enumerable.Repeat(httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack"), 1000));
sw.Stop();
var ms = sw.ElapsedMilliseconds;
Also call Dispose() on the returned HttpResponseMessage
HttpClient will fetch the whole response message and parse it into headers and body.
You may want to parallelize your access:
var httpclient = new HttpClient(); var ret = await httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack"); Stopwatch sw = new Stopwatch(); sw.Start(); var rets = await Task.WhenAll(Enumerable.Repeat(httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack"), 1000)); sw.Stop(); var ms = sw.ElapsedMilliseconds;
I want to give feedback on the performance of a single request using httpclient.
The next request using httpclient takes 80 milliseconds while keeping the previous connection. however, when i use a socket to initiate the request, it only takes 1ms.
You need to .Dispose() the returned HttpResponseMessage to release the request resources which you can do with a using statement
var httpclient = new HttpClient();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
using var ret = await httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack");
}
sw.Stop();
var ms = sw.ElapsedMilliseconds;
You need to
.Dispose()the returnedHttpResponseMessageto release the request resources which you can do with ausingstatementvar httpclient = new HttpClient(); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000; i++) { using var ret = await httpclient.GetAsync("http://127.0.0.1:5005/main/test?name=Jack"); } sw.Stop(); var ms = sw.ElapsedMilliseconds;
Adding dispose does not necessarily speed up the next request of httpclient.
when i use a socket to initiate the request, it only takes 1ms.
Do you also get all the data from the server and parse them in your socket tests? Could you share your socket test code so we can see we're comparing similar work being done?
This issue has been marked needs-author-action and may be missing some important information.
when i use a socket to initiate the request, it only takes 1ms.
Do you also get all the data from the server and parse them in your socket tests? Could you share your socket test code so we can see we're comparing similar work being done?
Here is my test code, requesting 1000 times in approximately 0.5 seconds. Web Server is running in release mode.
static async void testSocket()
{
var tcpClient = new TcpClient();
tcpClient.Connect( "127.0.0.1", 5005);
var netStream = tcpClient.GetStream();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
byte[] recBuffer = new byte[1024];
var content = @"GET /Main/Test?name=Jack HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
User-Agent: JmsInvoker
Accept: text/html
Accept-Encoding: deflate, br
Accept-Language: zh-CN,zh;q=0.9
Content-Length: 0
";
var data = Encoding.UTF8.GetBytes(content);
await netStream.WriteAsync(data);
var headers = new Dictionary<string, string>();
await ReadHeaders(netStream, headers);
var contentLength = 0;
if (headers.ContainsKey("Content-Length"))
{
int.TryParse(headers["Content-Length"], out contentLength);
}
if (contentLength > 0)
{
data = new byte[contentLength];
await netStream.ReadAtLeastAsync(new Memory<byte>(data), contentLength);
var text = Encoding.UTF8.GetString(data);
}
else if (headers.TryGetValue("Transfer-Encoding", out string transferEncoding) && transferEncoding == "chunked")
{
while (true)
{
var line = await ReadLine(netStream);
contentLength = Convert.ToInt32(line, 16);
if (contentLength == 0)
{
await ReadLine(netStream);
break;
}
else
{
data = new byte[contentLength];
await netStream.ReadAtLeastAsync(new Memory<byte>(data), contentLength);
var text = Encoding.UTF8.GetString(data);
await ReadLine(netStream);
}
}
}
}
sw.Stop();
var ms = sw.ElapsedMilliseconds;
}
static async Task<string> ReadHeaders(Stream stream, IDictionary<string, string> headers)
{
List<byte> lineBuffer = new List<byte>(1024);
string line = null;
string requestPathLine = null;
byte[] bData = new byte[1];
int readed;
int indexFlag;
while (true)
{
readed = await stream.ReadAsync(bData, 0, 1);
if (readed <= 0)
throw new SocketException();
if (bData[0] == 10)
{
if (lineBuffer.Count == 0)
break;
line = Encoding.UTF8.GetString(lineBuffer.ToArray());
lineBuffer.Clear();
if (requestPathLine == null)
requestPathLine = line;
if ((indexFlag = line.IndexOf(':', 0)) > 0 && indexFlag < line.Length - 1)
{
var key = line.Substring(0, indexFlag);
var value = line.Substring(indexFlag + 1).Trim();
if (headers.ContainsKey(key) == false)
{
headers[key] = value;
}
}
}
else if (bData[0] != 13)
{
lineBuffer.Add(bData[0]);
}
}
return requestPathLine;
}
static async Task<string> ReadLine(Stream stream)
{
List<byte> lineBuffer = new List<byte>(1024);
string line;
byte[] bData = new byte[1];
int readed;
while (true)
{
readed = await stream.ReadAsync(bData, 0, 1);
if (readed <= 0)
throw new SocketException();
if (bData[0] == 10)
{
line = Encoding.UTF8.GetString(lineBuffer.ToArray());
lineBuffer.Clear();
return line;
}
else if (bData[0] != 13)
{
lineBuffer.Add(bData[0]);
}
}
}
@simpleway2016 what is your platform? Can you also share the response from http://127.0.0.1:5005/main/test?name=Jack?
This issue has been marked needs-author-action and may be missing some important information.
@simpleway2016 what is your platform? Can you also share the response from
http://127.0.0.1:5005/main/test?name=Jack?
My platform: Windows 10 , .net 7.0 Here is my webapi code: (running in release mode)
[HttpGet]
public Task<string> Test(string name)
{
return Task.FromResult( "Hello " + name + DateTime.Now.ToString("HH:mm:ss"));
}
I cannot reproduce this; for me HttpClient is faster for the same scenario. Something weird must be going on in your environment. Do you have any firewalls, proxies configured? Can you share packet captures? (eg. with Wireshark)
I cannot reproduce this; for me
HttpClientis faster for the same scenario. Something weird must be going on in your environment. Do you have any firewalls, proxies configured? Can you share packet captures? (eg. with Wireshark)How long does it take for you to request 1000 times using httpclient?
The webapi must be confirmed to be running in release mode, otherwise using socket requests will also be very slow.
How long does it take for you to request 1000 times using httpclient?
~150ms. I was running everything in release.
How long does it take for you to request 1000 times using httpclient?
~150ms. I was running everything in release.
I have also noticed my problem. The httpclient must be running in release mode to be fast