Creating objects - round 2
It was pointed out that I had a skew in my test, I was also calling i.ToString() in a tight loop, which probably kills the numbers.
Here is the exact same benchmark, but using a constant string value, instead of calling i.ToString() all the time.
- Using new - 00.0177508 seconds (down from 00.3648117 seconds)
- Using Activator.CreateInstance - 06.3033382 seconds (down from 06.8242636 seconds)
- Using GetUninitializedObject - 02.8209057 seconds (down from 03.2422335 seconds)
- Using specialized dynamic method - 00.0417958 seconds (down from 00.4314517 seconds)
- Using generic dynamic method - 00.1189762 seconds (down from 00.5018288 seconds).
Here are some numbers to keep you entertained.
|Difference from previous approach||Time to create single instance||Iterations||Time||Method|
|Specialized dynamic method|
|Generic dynamic method|
It doesn't change the overall conclusion, by the way. There is just no way I can make myself work about 0.0000063 second.
I was also asked what the cost of creating dynamic method is, it comes to the tune of 00.0012487 seconds, for the generic version that I have shown. I would strongly encourage caching that, since (relative to creating the object itself) is seems expensive.
It is important to remember that dynamic method are also garbage collected, however, so we don't really have to worry about blowing the AppDomain if we use them.