Geeks With Blogs
John Conwell: aka Turbo Research in the visual exploration of data
I recently needed to change how an array lookup worked to make it more efficient, and decided to use the List<T>.BinarySearch to do the lookup.  The class that contained this lookup had a generic parameter, and was constrained like so:

public class SortedNameList<T> where T : class, INameValueItem, new()

where the T of List<T> was the same as the class generic parameter.

In order to do the BinarySearch, List<T> required an input of type T to search against.  Since I only had the value of the property that will be compared against (an int), I needed to create a new temp instance of T, set the value, and then pass it into BinarySearch().

My unit tests passed, all the functionality was good, and I was happy.  Then I ran the my app under a profiler to see how much faster my fancy BinarySearch was. 

To my surprise, the time spent doing the binary search calls was almost exactly the same as a linear lookup (over 1.2 million searches)!  What the heck?  I know that creating a new temp object each lookup isn't very efficient, but it shouldn't make that much of a difference.

So after looking a bit deeper and doing some more performance tests, I found out that creating a new instance of a generic ("T tmp = new T()") is sloooooo.  How slow?  How about 30X slower!  WOW...I had no idea!

And its not that it takes the CLR some time to figure out how to create a new T, where most of the time is on the first instance, and the rest speed up.  Nope, the duration to create a new T is consistant, from the first instance to the millionth instance.

Good to know...dont do that in a high volume area Posted on Friday, June 13, 2008 8:40 AM Code Performance | Back to top

Comments on this post: Creating an instance of a generic paremeter is slooooo

# re: Creating an instance of a generic paremeter is slooooo
Requesting Gravatar...

"Generic" and "Performance" are not compatible...
Btw: I like your blog, dude :)
Left by Yngwie on Jan 05, 2009 6:02 AM

Your comment:
 (will show your gravatar)

Copyright © John Conwell | Powered by: