So I sat in on some c++ training classes they were holding at work and I've been thinking more and more about performance. Couple that with the occasional post on Rico Mariani's excellent blog, and you can color me interested.
Of the many considerations there are to make, here's a few of the things that I've been focusing on to try and maximize performance ...
- Temporary objects: Everytime you create a temporary variable (in a loop for example), memory must be allocated, the variable initialized, and eventually the memory reclaimed by the GC. So in the past when I would have done something like this:
if (lstRequestor.Items.FindByValue(uname) != null)
{
ListItem itm = lstRequestor.Items.FindByValue(uname);
itm.Selected = true;
}
Notice that not only am I calling FindByValue twice, but I'm declaring a temporary variable for ListItem before using it. Now, in this case, it's probably not that big of a deal since ListItem is a reference type, but if the object I wanted to operate on was a value type, then a copy would have been made. I now do something like this:
{
ListItem itm;
if ((itm = lstRequestor.Items.FindByValue(uname)) != null)
{
itm.Selected = true;
}
}
I've introduced two optimizations. 1) I'm assigning the result of FindByVAlue and checking the result for null in one fell swoop so I don't have to call it twice. 2) Though I'm still using a temporary variable, I limited the scope by placed curly braces around that snippet of code. That way, the reference itm is not kept around until the end of the procedure and the GC can release it next time it runs.
Properly implementing IDisposable: Once you do your thing, make sure you call GC.SuppressFinalize();
Cache Cache Cache: Especially in an ASP.NET application, properly designing your caching strategy will give you mad amounts of performance gains. And I like that :-)