Very incisive! I checked the assembly code and verified your hypothesis. The integer-to-floating cast of numeric_cast was really inlined by the compiler, meanwhile the other two were using function call to invoke numeric_cast. So maybe the better solution is to force inline for numeric_cast in all cases.

On Tue, Oct 16, 2012 at 4:12 PM, John Maddock <boost.regex@virgin.net> wrote:
results:

Native Integer Cast: 26729 nanoseconds
Boost Integer Cast: 26449 nanoseconds
Native Integer-Floating Cast: 105479 nanoseconds
Boost Integer-Floating Cast: 105455 nanoseconds
Native Floating-Integer Cast: 168933 nanoseconds
Boost Floating-Integer Cast: 453505 nanoseconds


so no overhead in Integer-Integer or Integer-Floating. But Floating-Integer has bad performance.

That's sort of what I would expect - think about it - if the cast is to the same or a wider type, then there is no check, and numeric_cast and static_cast do the same thing.  However for a narrowing cast (float to integer), then at the very least there has to be an extra if statement to test whether the value being cast is in range - that would normally roughly double the runtime cost.  But there *may* be another hidden cost: depending on the loop the compiler may decide not to inline the numeric_cast in order to give a tighter loop, and the cost of the function call would add a big chunk of time.  Plus the extra code associated with the error handling if the value is out of range adds a certain amount of code bloat to the loop, reducing code locality.  But the thing is you can't avoid this if you want the runtime check.  There's no such thing as a free lunch sadly.

John.
_______________________________________________
Boost-users mailing list
Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users