if a and b are double, does anyone know if
((dynamic)a) + ((dynamic) b)
is faster or slower than
Func<double,double,double>((x,y) => x + y)(a, b)
And can you explain why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first version will always be slower. In very simple terms with this version everything that the compiler can do at compile time has now to be done at runtime, ie. checking the types of a and b, finding if they support the + operator and so on. It will cache a lot of this stuff, but still it is much more work than invoking a delegate.
In the second version all those checks can be done during compilation. The cost at runtime are only the creation and invocation of the delegate.
For example, consider those methods:
in contrast to
This is what the compiler generates from the first method:
I’ve done some crude measurements and on my machine the first version is about 5 times slower than the second. I have to admit that I would have expected the difference to be larger.
Update: As for a prove why this is slower than a delegate: Given that the generated call site code also involves the invocation of a delegate (
arg_98_0), this piece of code (invocation of delegate + X) must necessarily be slower than using a delegate only.