Tuesday 24 February 2015

ASP.NET Tips #25 - Profile, don’t speculate!

Performance is something you should be concerned with from the start, by following best practices and general guidelines, rather than focusing on nitty gritty details. However, there often comes a time where you need to optimize your code to make it faster.

It's tempting to rely on your gut and focus on spots of code that you think are slow, but if you do that you run the risk of speeding up code that doesn't make much difference to overall performance. After all, even if you double the performance of code that only executes for 1% of overall time, the end result will be negligible.

Don’t speculate. Use code profilers to measure where time is being spent (either optimize for speed or for memory use), so you can focus your energy on the optimizations that will have the greatest impact on the overall performance of your system.

When in production, carefully consider what you need to log

Many people deploy to production without checking how logging is currently configured. It is always advisable to check whether your policy is to have logging on or off by default and, if on, what level you should be targeting. In addition, you should check which targets you are outputting to, what archiving strategy you have, and whether your logging infrastructure allows for async logging.

Tuesday 17 February 2015

ASP.NET Tips #24 - Before tackling any website performance issue, first verify the problem isn’t on the client

Traditionally, many performance problems have been rooted in either the database or application server. However, with the proliferation of advanced JavaScript frameworks such as Backbone.js or jQuery, performance problems are increasingly starting to appear on the client.

Rather than immediately attempting to diagnose a performance problem on the server, first use a free browser-based tool such as Google Chrome Developer Tools to ensure that the problem isn't actually occurring on the client.

You may just save yourself a lot of time tracking down performance problems on the wrong end of your site.

Don’t underestimate the value of the UI when tackling performance problems

Simple UI tricks, such as progress bars, redirecting users' attention using animation, or placing slower loading sections at the bottom of a page or offscreen, can often 'fix' a performance problem without the need to tune the underlying code.

These UI tricks are an important tool to have in your performance tuning toolbox and can be much quicker and easier than addressing the underlying issue. They can act as a holdover until you have the time to devote to the core problem.

Throw hardware at the problem, not developers

As developers, we often want to fix problems with code, but don't be afraid to 'put the compiler down' and throw some hardware at the problem. Performance problems caused by disk I/O bottlenecks or paging out of RAM can often be solved by a faster hard drive or more RAM.

CPU bound bottlenecks can often be solved by a new machine with a faster processor. As counterintuitive as it sounds, addressing problems by buying a new machine or upgrading an aging one is often much cheaper than having a developer troubleshoot, diagnose, and correct a deep performance problem.

And the rest of your website will get a performance kick to boot!

Don't assume that problems can only arise from business logic

When beginning to diagnose performance problems, we often assume the problem is in our business logic. Don't forget that the areas of our code that provide infrastructure can cause problems as well.

Areas such as HttpHandlers, HtmlHelpers, mapping, logging, or IoC frameworks are increasingly at the root of performance problems. While business logic still causes its share of problems, infrastructure code is quickly gaining in the performance problem race.

Wednesday 11 February 2015

ASP.NET Tips #23 - Want to build scalable websites and services? Work asynchronously

One of the secrets to producing scalable websites and services is to perform all your I/O operations asynchronously to avoid blocking threads.

When your thread issues a synchronous I/O request, the Windows kernel blocks the thread. This causes the thread pool to create a new thread, which allocates a lot of memory and wastes precious CPU time. Calling xxxAsync method and using C#'s async/await keywords allows your thread to return to the thread pool so it can be used for other things. This reduces the resource consumption of your app, allowing it to use more memory and improving response time to your clients.

Take advantage of .NET 4.5 async/await constructs

With the arrival of .NET 4.5, writing async/await code correctly is easier than ever. Like any tool, it should be only applied where it makes most sense – in web use-cases this usually revolves around I/O operations (i.e. reading from disk, any network operation, database operations, sending email, file transfer over FTP or calls to web services).

Be careful of variable allocations

Inside async methods, .NET will create a state machine behind the scenes to lift out local variables for you. That way, when the method resumes, all the values are still there. It's a fantastic feature, but at it's not yet smart enough to tell if you still need a particular variable.

Consider this code example:

var today = DateTime.Now;
var tomorrow = today.AddDays(1);
await MyTaskHere();
Console.WriteLine(tomorrow);

In this example we have two DateTime variables declared - yes, it’s a trivial example, but it proves the point. After the await, we only need to use the "tomorrow" value. However, the state machine will lift out both the today and tomorrow variables. In this example, the object that is used to retain state for the async operation is larger than necessary. This means more variable declarations, and eventually this can lead to additional GC cycles, and so on.

To avoid this, and reduce the size of the state-tracking object, you could re-write the code like so:

var tomorrow = DateTime.Now.AddDays(1);
await MyTaskHere();
Console.WriteLine(tomorrow);

By being smart with the variables that you have inside an async method, you can help control the size of the state-tracking object.

Using the keyword await doesn't make the work asynchronous

The async/await pattern makes it easy to write code that depends on work that's done asynchronously, but it doesn't turn synchronous code into asynchronous code.

If you await an async Task method that does some work and returns a value, the work will be done synchronously – the original method is waiting for a Task object to be returned which it can then await on, but the only Task it gets is one which is wrapped around the return value and set to “completed”. This is useful if you are chaining async methods, but in this case it is confusing.

By the time the awaiting method sees the Task, it's already complete, so the code continues to execute synchronously. If you want to do work asynchronously, you need to pass back a Task object representing the work in progress. One way of doing this is by using Task.Run().

Don’t use async/await for short methods

Async/await is great for avoiding blocking while potentially time-consuming work is performed, but there are overheads associated with running an async method: the current execution context has to be captured, there is a thread transition, and a state machine is built through which your code runs. The cost of this is comparatively negligible when the asynchronous work takes a long time, but it's worth keeping in mind.

Avoid using async/await for very short methods or having await statements in tight loops (run the whole loop asynchronously instead). Microsoft recommends that any method that might take longer than 50ms to return should run asynchronously, so you may wish to use this figure to determine whether it's worth using the async/await pattern.

Have a look at :

https://msdn.microsoft.com/en-us/library/hh191443.aspx

Never call .Wait() or .Result on a Task

Never call .Wait() or .Result on a Task within your application; it can bring your server crashing down. It shouldn't be necessary to mention this, but so many examples do this that it's worth reiterating.

Sunday 8 February 2015

ASP.NET Tips #22 - Removing X-Powered-By ASP.Net and other version headers

Most likely you do not want these headers to be displayed in your responses:

  • Server Microsoft-IIS/7.5
  • X-AspNetMvc-Version 4.0
  • X-AspNet-Version 4.0.303319
  • X-Powered-By ASP.NET

Removing X-AspNet-Version, In web.config add this:

<system.web>
   <httpRuntime enableVersionHeader="false"/>
</system.web>

Removing X-AspNetMvc-Version, In global.asax.cs add this:

protected void Application_Start()
{
   MvcHandler.DisableMvcResponseHeader = true;
}

Removing or changing X-Powered-By, IIS 7.5 - You can also remove the X-Powered-By header by including these lines to the element in Web.config:

<system.webServer>
   <httpProtocol>
      <customHeaders>
         <clear />
         <remove name="X-Powered-By" />
      </customHeaders>
   </httpProtocol>
</system.webServer>

Removing Server, In global.asax.cs add this:

protected void Application_PreSendRequestHeaders()
{
   Response.Headers.Remove("Server");
}

Wednesday 4 February 2015

ASP.NET Tips #21 - Remove unused View Engines in MVC

If you're an ASP.NET MVC developer, you might not know that ASP.NET still loads the View Engines for both Razor and Web Forms by default. This can cause performance issues because MVC will normally look for Web Forms views first, before switching over to the Razor views if it can't find them.

You can quickly eliminate this performance issue by adding the following two lines to your Global.asax, in the Application_Start():

protected void Application_Start()
{
   ViewEngines.Engines.Clear();
   ViewEngines.Engines.Add(new RazorViewEngine());
}

Goodbye Web Forms View Engine!