我认为我发现使用相同的连接组名称发送给example.com
的100个请求比没有此请求会导致更快的总响应时间。实际上,似乎唯一的因素是我拨打电话的顺序(合并的电话,然后是非合并的电话,反之亦然)。
using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
public class WebRequestTests
{
public WebRequestTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper;
private readonly ITestOutputHelper _testOutputHelper;
private const string CONNECTION_GROUP_NAME = nameof(CONNECTION_GROUP_NAME);
private static TimeSpan Pooling(int numberOfRequests)
{
var requests = new WebRequest[numberOfRequests];
var responses = new WebResponse[numberOfRequests];
for (var i = 0; i < numberOfRequests; i++)
{
var request = WebRequest.Create("http://example.com");
requests[i] = request;
}
var stopwatch = Stopwatch.StartNew();
Parallel.For(0, numberOfRequests, i => { responses[i] = requests[i].GetResponse(); });
stopwatch.Stop();
return stopwatch.Elapsed;
}
private static TimeSpan NoPooling(int numberOfRequests)
{
var requests = new WebRequest[numberOfRequests];
var responses = new WebResponse[numberOfRequests];
for (var i = 0; i < numberOfRequests; i++)
{
var request = WebRequest.Create("http://example.com");
request.ConnectionGroupName = CONNECTION_GROUP_NAME;
requests[i] = request;
}
var stopwatch = Stopwatch.StartNew();
Parallel.For(0, numberOfRequests, i => { responses[i] = requests[i].GetResponse(); });
stopwatch.Stop();
return stopwatch.Elapsed;
}
[Fact]
public void ConnectionGroupPerformance()
{
const int numberOfRequests = 1000;
_testOutputHelper.WriteLine($"Number of requests: {numberOfRequests}");
var poolingDuration = Pooling(numberOfRequests);
var noPoolingDuration = NoPooling(numberOfRequests);
var message = $"No Pooling {noPoolingDuration:g}, Pooling {poolingDuration:g}";
_testOutputHelper.WriteLine(message);
Assert.True(poolingDuration < noPoolingDuration, message);
}
}
我还尝试为非池连接分配一个随机的组名,以防空字符串/空值作为组名。
我在这里想念什么?