lundi 7 septembre 2015

C# - Why does dynamic binding is not faster?

Consider the following code:

delegate string StringToString(string s);

MethodInfo trimMethod = typeof(string).GetMethod("Trim", new Type[0]);
var trim = (StringToString)Delegate.CreateDelegate
           (typeof(StringToString), trimMethod);
for (int i = 0; i < 1000000; i++)
     trim("test");

The above code dynamically calls string’s Trim method a million times without significant overhead. Now if we run the following code:

for (int i = 0; i < 1000000; i++)
     "test".Trim();

It's faster than the first one. The first one must be faster because the costly dynamic binding happens just once.

My question is: why does the second one run faster than the first one?





Aucun commentaire:

Enregistrer un commentaire