Marcelo Calbucci

Startup Score:

Successes: 0.1+0.5
Failures: 1
In progress: 1

Wednesday, January 31, 2007

C# tip: Optmizing ArrayList usage

 

    It has been a while since I wrote a tip of development. This one is pretty good, I think.

 

    In .NET 1.0 and 1.1, each ArrayList would pre-allocate space for 16 elements, which means 64 bytes just for the pointer storage. Then, the .NET team did something very smart. They instrumented several real world applications and they found out that most of the ArrayList created had... zero elements!

 

    That is right, most of the ArrayList allocated in an application are never used. So on .NET 2.0 they changed the default allocation to only 4 elements, which saves 48 bytes per ArrayList not being used.

 

     I thought that change was great, but it had near zero impact on Sampa, because I knew the cost of allocating an ArrayList so I always delayed it until I knew I would use it.

 

    But I went one step further.

 

    As the .NET development guidelines recommend, if your function returns an ArrayList, it is better to make it return an empty array than a null pointer. If you are consistent, you avoid having to compare for both cases when calling a function.

 

    Turns out, that a lot of functions will return empty ArrayList on Sampa, and probably on your application too. The solution: Create a static ArrayList with zero elements and used it every time you'll return an empty array instead of allocating a new ArrayList and return it.

 

    Just make sure that static ArrayList is created properly with readonly flag on the variable and read-only attribute on the array:

 

static public readonly ArrayList EmptyArray = ArrayList.ReadOnly(new ArrayList());

 

    That saved us a ton of memory. Each request might be "using" 300 hundred or more empty ArrayList. If each ArrayList takes about 40 bytes, we are saving 12KB per request. At 100 requests/second, that is 1.2MB less (or 30K objects) that the Garbage Collector needs to worry about (per second!).

 

 

blog comments powered by Disqus