It is not a matter of SFML, the same question could arise with other kind of similar code (e.g. most event loops, finite state automatons, bytecode interpreters; read also about threaded code).
Regarding performance, in principle, a switch
would often be slightly faster, but you should benchmark (and some compilers might optimize a sequence of if
into the equivalent of switch
or vice versa). In your case, it should not really matter (because most of the time your application would wait for an event in window.pollEvent(event)
....).
Assuming no heavy optimization happens, I would imagine that some rare switches might be slightly slower, because e.g. of L1 I-cache being full because the hot code would be too large, etc... But that scenario is unusual.
If you are curious, read this A Superoptimizer Analysis of Multiway Branch Code Generation paper (by R.Sayle) about switch optimization.
Regarding readability, the switch
is a also more readable.
The readability argument seems the most relevant to me; leave micro-optimizations to the compiler, they are doing quite well. Of course, don't forget to compile with g++ -Wall -O2 -mcpu=native
and perhaps replace -O2
by -O3
(and perhaps even compile and link with g++ -flto -O3 -mcpu=native
if you care a lot about performance)
(practically speaking, readability is the only thing which should matter to you in that case)
If you want to understand how and "why" the compiler optimizes, consider adding to your -O2
flag -fverbose-asm -S
(then look into the generated .s
file) or even compiling with -fdump-tree-all
(you'll get hundreds of compiler dump files, corresponding to various optimizations passes in GCC...) with some optimization switches (e.g. -O2
or -O3
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…