views:

402

answers:

6

Try to see which cast is faster (not necessary better): new c++ case or old fashion C style cast. Any ideas?

+3  A: 

Take a look at the assembly using each method. If it differs use a profiler.

Yacoby
+21  A: 

There should be no difference at all if you compare int() to equivalent functionality of static_cast<int>().

Using VC2008:

    double d = 10.5;
013A13EE  fld         qword ptr [__real@4025000000000000 (13A5840h)] 
013A13F4  fstp        qword ptr [d] 
    int x = int(d);
013A13F7  fld         qword ptr [d] 
013A13FA  call        @ILT+215(__ftol2_sse) (13A10DCh) 
013A13FF  mov         dword ptr [x],eax 
    int y = static_cast<int>(d);
013A1402  fld         qword ptr [d] 
013A1405  call        @ILT+215(__ftol2_sse) (13A10DCh) 
013A140A  mov         dword ptr [y],eax

Obviously, it is 100% the same!

AraK
+1. Assembly is always nice for such things.
Joey
This doesn't look sexy to me :) A sexy one would use SSE instructuions without involving the FPU at all :) (I thought SSE was used by default in VC already).
AndreyT
@AndreyT It does :) the code in the answer was produced in debugging mode. If you try to compile it with optimizations, it does use SSE instructions.
AraK
-1(if I could). It is not obviously. Your answer proves that it is the same only in certain version of VS2008.
big-z
+1  A: 

They are same as it is resolved during compile time itself and there is no runtime overhead. Even if there was some difference I really wouldn't bother too much about these tiny (not even micro) optimizations.

Naveen
+1  A: 

No difference whatsoever.

When it comes to such basic constructs as a single cast, once two constructs have the same semantic meaning, their performace will be perfectly identical, and the machine code generated for these constructs will be the same.

AndreyT
A: 

When you choice makes little difference to the code, I'd pick the one which looks more familiar to later programmers. Making code easier to understand by others is always worth considering. In this case, I'd stick to int(…) for that reason.

Tim
Why would you assume that int(...) will be more familiar, though? It actually appears not to be valid in C, being perhaps rather a "pseudo-constructor" call of C++. - Also, by not being explicit about the type of cast, why should it make code easier to understand?
UncleBens
Casts are nothing to be toyed with and should therefore be easy to spot. That's what the C++-style casts are.
mxp
+2  A: 

I believe that the actual result is implementation defined. You should check it in your version of compiler. But I believe that it will give the same result in most modern compilers. And in C++ you shouldn't use C-cast, instead use C++ casts - it will allow you to find errors at compile time.

big-z
+1 for mentioning compile-time checks
mxp