How to get a Fast .Net Http Request

后端 未结 3 1624
不知归路
不知归路 2021-02-03 11:26

I need an Http request that I can use in .Net which takes under 100 ms. I\'m able to achieve this in my browser so I really don\'t see why this is such a problem in code.

3条回答
  •  感情败类
    2021-02-03 11:55

    Use the StopWatch class to get accurate timings.

    Then, make sure you're not seeing the results of un-optimized code or JIT compilation by running your timing test several times in Release code. Discard the first few calls to remove he impact of JIT and then take the mean tidings of the rest.

    VS.NET has the ability to measure performance, and you might also want to use something like Fiddler to see how much time you're spending "on the wire" and sanity check that it's not your IIS/web server causing the delays.

    500ms is a very long time, and it's possible to be in the 10s of ms with these classes, so don't give up hope (yet).

    Update #1:

    This is a great article that talks about micro benchmarking and what's needed to avoid seeing things like JIT:

    http://blogs.msdn.com/b/vancem/archive/2009/02/06/measureit-update-tool-for-doing-microbenchmarks.aspx

    You're not quite micro-benchmarking, but there are lots of best practices in here.

    Update #2:

    So, I wrote this console app (using VS.NET 2010)...

    class Program
    {
        static void Main(string[] args)
        {
            var stopwatch = Stopwatch.StartNew();
            var req = (HttpWebRequest)WebRequest.Create("http://localhost");
            var response = req.GetResponse();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);            
        }
    }
    

    ... and Ctrl-F5'd it. It was compiled as debug, but I ran it without debugging, and I got 63ms. I'm running this on my Windows 7 laptop, and so http://localhost brings back the default IIS7 home page. Running it again I get similar times.

    Running a Release build gives times in the 50ms to 55ms range.

    This is the order of magnitude I'd expect. Clearly, if your website is performing an ASP.NET recompile, or recycling the app pool, or doing lots of back end processing, then your timings will differ. If your markup is massive then it will also differ, but none of the classes you're using client side should be the rate limiting steps here. It'll be the network hope and/or the remote app processing.

提交回复
热议问题