You are trying to improve the performance of the caching algorithm on your ASP.NET site and wonder what problems exist with SetCacheability and examples on the Internet. Use SetCacheability more efficiently. Here we examine the SetCacheability method in ASP.NET, using the C# programming language.
=== ASP.NET SetCacheability test === Calling SetCacheability decreased performance. It did not change the default setting in ASP.NET. Default: 1.57 seconds [faster] SetCacheability(Private): 2.14 seconds
First, Response.Cache.SetCacheability is a method you can call to modify the Cache-Control header. There are several enum values you can specify. The problem we see here is with HttpCacheability.Private. Here we see how you can streamline your caching code and reduce processing time by removing a call to Cache.SetCacheability(HttpCacheability.Private). As stated, HttpCacheability.Private is the default value for the cache. You do not need to initialize your Cache to it.
using System;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Trace.Write("Start");
HttpResponse r = Response; // Get response
TimeSpan span = new TimeSpan(1, 0, 0); // Example time span
for (int i = 0; i < 1000000; i++)
{
#if SLOW
HttpCachePolicy p = r.Cache;
p.SetCacheability(HttpCacheability.Private);
p.SetMaxAge(span);
#else
r.Cache.SetMaxAge(span);
#endif
}
Trace.Write("End");
}
}Description. The code has a loop that benchmarks the page load speed. It is surrounded by Trace.Write calls, which keep track of the elapsed time.
SetCacheability call. In the slow block, you can see that the SetCacheability method is called with a parameter of HttpCacheability.Private. This is wasteful because it is the default value.
In the micro-benchmark here, the code that avoids setting the cacheability of the page to a value it is already set to by default took 1.57 s. The code that calls SetCacheability took 2.14 s.
Interpretation of results. Looking into SetCacheability, you can see that it has many lines of internal logic, including elaborate error-handling. This is necessary for a robust framework. However, in this case it is wasteful.
Here we saw that calling SetCacheability(HttpCacheability.Private) is not useful and slows down page page processing. The only time it is useful is if for some reason you have already called the function to change the value. There are example pages that show this call being used in the documentation on MSDN and elsewhere. However, MSDN clearly states it is the default value, so the documentation is not effective.