The best thing Microsoft ever did for C# was to create it with a syntax similar to C and C++.
The worst thing Microsoft ever did for C# was to create it with a syntax similar to C and C++.
C and C++ are unmanaged languages, so an apple in C could be an orange in C#, or it could be an orangutan.
The following code was written circa-2003, by a programmer who was probably a C++ programmer turned .NET, and didn’t give a second thought to including a finalizer in his code. A telling indication was that he even labeled it as a ‘destructor’.
Warning: Here There Be Dragons.
{
private ArrayList objectFilters = new ArrayList();
//snip…
#region Destructor
~AndObjectFilter()
{
this.objectFilters.Clear();
}
#endregion
}
There are (at least) three things wrong with this code:
- Use of a finalizer.
- Use of a finalizer to clear an ArrayList.
- Using an ArrayList.
Use of a Finalizer
Finalizers in C# are used to allow the developer to force the garbage collector to run certain code before garbage collecting an object. There’s a wealth of material written on Finalizers, and I won’t repeat it all here:
- Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework by Jeffrey Richter
- Stack Overflow: Finalize and Dispose Pattern in C#
- Two things to avoid for better Memory usage
To summarize what all of these points say:
Don’t use Finalizers if:
- Your class consists solely of managed code (or)
- You plan on implementing the IDisposable Pattern on that class
Should be pretty easy to remember, unless you’re a C++ programmer that doesn’t read up on new-fangled technology.
Use of a Finalizer to clear an ArrayList
Disregarding for the moment that you should never, ever use a finalizer like the code shown above does, there’s a second point:
Why in the name of all that is holy is the programmer using the Clear() method, in the finalizer, no less?
- They have no idea what the Finalize method actually does (See Use of a Finalizer above)
- They really have no idea what ‘managed code’ means
- They have no idea what Clear() does
The ArrayList.Clear() method simply clears out the contents of the array. The capacity of the ArrayList is still set, probably not what the programmer wanted to do.
Using an ArrayList
The code is presently in .NET 2.0 and has been for years, although it is a Micro optimization, even using a List<object> performs better than an ArrayList:
Inserting into ArrayList took: 8.27msInserting into List took: 0.002msEnumerating ArrayList took: 2.284msEnumerating List took: 0.413ms
That’s over a 4000% difference in Insertion, and List is 5.5 times faster for enumeration!
Just because something quacks like a duck doesn’t make it a duck. Sometimes it’s actually a really expensive C# operation that’s better left out of your code.