Taking this struct:

struct Foo
{
    float m_foo;
    // no other member
};

// A Foo object.
Foo f;

Which is more costly?

float result = std::sin(f.m_foo);

or

float result = std::sin(*(reinterpret_cast<float*>(&f)));
// f can be interpreted like float in this case

I think the second case is faster, but i don't have sure because i don't know how the compiler will handle it. What you can tell me about it?

有帮助吗?

解决方案

Which is more costly?

IME, the one invoking Undefined Behavior is always more costly in the end.

If you want to port this to some new platform, or another compiler, or a new version of your compiler, such code might blow up. Or it might make some other, innocent looking code blow up. Or it might do so only on Sundays, when your customers cannot call support. (They will call on Monday then, so you should take off on Monday as often as possible if you write such code.) Or it might only do so when your boss is around, or at full moon, or at compiler versions built at the first of the month.

If you have some concrete case where you need to speed up some code, and you found, through profiling, that this piece of code is a bottleneck, then measure whether this brings any relevant performance advantages, using your real application and real data. If it does, then in God's name use it in this one place, but put some very visible comment there, explaining what you do and why.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top