Question

I need to GET contents of a specific URL. It's a simple and straightforward task, though I want is as efficient as possible.

Does WebClient or HttpWebRequest take less memory? Which class will complete the same task faster? Which class takes less time to initialize?

Was it helpful?

Solution

WebClient is just a wrapper around HttpWebRequest. Using WebClient is potentially slightly (on the order of a few milliseconds) slower than using HttpWebRequest directly. But that "inefficiency" comes with huge benefits: it requires less code, is easier to use, and you're less likely to make a mistake when using it. Consider, for example, retrieving the text of a Web page using WebClient:

var client = new WebClient();
var text = client.DownloadString("http://example.com/page.html");

Contrast that to HttpWebRequest:

string text;
var request = (HttpWebRequest)WebRequest.Create("http://example.com/page.html");
using (var response = request.GetResponse())
{
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        text = reader.ReadToEnd();
    }
}

Things get really interesting if you want to download and save to file. With WebClient, it's a simple matter of calling DownloadFile. With HttpWebRequest, you have to create a reading loop, etc. The number of ways you can make a mistake with HttpWebRequest is truly astounding. I know 'cause I've made a lot of them.

Now consider downloading two different pages. With WebClient you can write:

var client = new WebClient();
var page1 = client.DownloadString(page1Url);
var page2 = client.DownloadString(page2Url);

Done. With HttpWebRequest, you'd have to duplicate the code above, or wrap that code in a method. But if you're going to wrap it in a method, then why not just use WebClient, which already does it for you?

When you consider that a request to a fast Web site will probably take on the order of 100 to 500 milliseconds, the few milliseconds' overhead that WebClient adds will amount to at most single-digit percentage of the total time.

Use WebClient for simple things. Only use HttpWebRequest if you require the additional low-level control that it offers. Speed considerations among the two are irrelevant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top