HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

HTTP Performance Test in C#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
testhttpperformance

Problem

I wrote a script to test how long it takes to make requests against a url. It takes a list of urls, an array of concurrent requests, and a number of times to attempt the test. How could I improve on this?

//https://www.nuget.org/packages/RestSharp

string baseUrl = "http://localhost";
void Main()
{
    var urls = new string[] { 
        "/some/end/point",
    };

    var concurrentRequests = new int[]{ 1, 5, 25, 50, 100, 500, 1000};
    var numberOfTurns = 10;
    RunTests(urls, concurrentRequests, numberOfTurns);

}

private void RunTests(string[] urls, int[] concurrentRequests,  int numberOfTimes = 1)
{
    for(var i = 0; i    
    {
         RunTest(urls, e);
    }); 
}
private void RunTest(string[] sites, int iterations, string description = "")
{
    var action = GetAction();

    var watch = new Stopwatch(); 
   // Construct started tasks
   Task[] tasks = new Task[sites.Count()];
   watch.Start();

   for(int j = 0; j .Factory.StartNew(action, sites[i]);
        }
   }
   try
   {
       Task.WaitAll(tasks);
   }
   catch (AggregateException e)
   {
       Console.WriteLine("\nThe following exceptions have been thrown by WaitAll()");
       for (int j = 0; j   GetAction()
{
    baseUrl = baseUrl.Trim('/');
    return (object obj) =>
   {
        var str = (string)obj;
        var client = new RestClient(baseUrl);
        client.Authenticator = new NtlmAuthenticator();
        var request = new RestRequest(str, Method.GET);
        request.AddHeader("Accept", "text/html");
        var response = client.Execute(request);     
        return (response != null);
   };
}

Solution

You're not always using var in what I think of as a good way. We should only use the keyword when it's obvious what type the variable is. Consider this line.

Task[] tasks = new Task[sites.Count()];


It's completely obvious what tasks is because you're newing it up right there on that line. There's no reason not to simplify by using var.

But here, you have the opposite problem.

var response = client.Execute(request);


It is not obvious what the return type is, so you shouldn't be using var.

Code Snippets

Task<bool>[] tasks = new Task<bool>[sites.Count()];
var response = client.Execute(request);

Context

StackExchange Code Review Q#71789, answer score: 5

Revisions (0)

No revisions yet.