1
votes

I was building a method today in my WebAPI2. and came to the question if i should make my method a void or keep it as IHttpActionResult?

As advantage i see that IHttpActionResult can return any response code. What is the advantage of the void approach? is it faster or is the only difference that it always response 200 (or is it 204?).

Does somebody know which one is faster? or if it has any other major difference than the ones that i have named? (this includes the fact that void can't respond anything and IHttpActionResult can.......)

2

2 Answers

5
votes

@Felipe Oriani, you where totaly true.. I was curious so i did the test. See this amazing output.

Test shown

  • Void Avg response time is 2.075 ms
  • IHttpActionResult Avg response time is 1.651 ms!

So that is a difference of 0.424 ms

This was with the following webAPI code

[Route("test/void")]
public void GetFirst()
{
    StringBuilder stringbuilder = new StringBuilder();
    for (int i = 0; i < 20; i++)
    {
        stringbuilder.Append("something");
    }
    //Thread.Sleep(1000);
}

[Route("test/IHttpActionResult")]
public IHttpActionResult GetSecond()
{
    StringBuilder stringbuilder = new StringBuilder();
    for (int i = 0; i < 20; i++)
    {
        stringbuilder.Append("something");
    }
    //Thread.Sleep(1000);
    return Ok();
}

Also i tried giving the webAPI more work on each request.. to see if the difference stays the same, or if for an longer action it's a real improvement to use IHttpActionResult instead of void?

I set the iteration to 200000 and uncommented the Thread.Sleep(1000) in the WebAPI code

Now the results:

  • Void Avg response time is 11.64 ms
  • IHttpActionResult Avg response time is 11.11 ms

So that is a difference of 0.53 ms

To which i can conclude and confirm, that what you say is true. And IHttpActionREsult is indeed faster then void. Only the difference is to minor to really notice something. But if your looking for the minor mini optimalisations? this is one of them!

The image below for the result! second test result

1
votes

Every message from an asp.net web api application return an http status code. An exception is expensive, so, if you pass this to the web api, the framework should know how to lead with this and change to a http message result.

There is no extremelly difference. A void action method in web api will return something diferent from 200 - OK if the code throw an exceptionActually I think it's even more expensive than a method with a type in result because the asp.net framework need to get the exception and change it to a http message as I said before.

If you specify an http message in your action method, you know what exactly you are responding to the client (I mean, the http status code as least). I enjoy working with HttpResponseMessage and create responses with the specific http status code.