Some while ago, i saw the following code in a project i’m working:
string[] a = (string[])Array.CreateInstance(typeof(string), 10);
And then i became shocked… I called him every name in the book. And why? Because the complication above could be replaced simply by:
string[] a = new string[10];
And there are 2 reasons:
First: The IL generated by the CreateInstance is much more complex than the IL generated by the new operator:
Create Instance IL:
IL_0000: ldtoken [mscorlib]System.String
IL_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_000a: ldc.i4.s 10
IL_000c: call class [mscorlib]System.Array [mscorlib]System.Array::CreateInstance(class [mscorlib]System.Type,
int32)
new operator IL:
IL_0011: castclass string[]
IL_0016: stloc.0
IL_0017: ldc.i4.s 10
IL_0019: newarr [mscorlib]System.String
Second: because the CreateInstance uses reflection and, because of that, the operation is much more slow. Here are the times, in Miliseconds, for 1 million iterations of each operation:
CreateInstance: 406,2422 ms
New: 31,2494 ms
Has you can see, reflection is very expensive. In this case, just the line of code with CreateInstance is 13 times more expensive then the one with the new operator.
So, be careful where and when you use reflection. The bad use of it can result in a performance break of your application.
I would add a third reason:
third: why complicate your life and code with reflection when you can just use pure C# code?
This also applies to Java of course, which is my main language
Riccardo, I agree. In fact I wouldn’t say its the third reason. The first and only important reason is because when you read the code it is obvious what it does.
Because the compiler has generated more code, or is slower, is largely irrelevant. That is an issue for the compiler writers to ponder.
Riccardo you are 100% correct. I actually forgot the most obvious reason of all
Ok
I also agree with Matt: new string[10] talks for itself, array.createInstance… not that much!
The thing I don’t understand about this, is why?
It’s a bit like what Riccardo said, as to why someone would complicate their life this much over something so trivial. I’m not sure whether the original author (of the uselessly “reflected” code) was a genius or just plain stupid?