Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

c++ - Events is SFML. Switch statement VS if statement

I have some code like this:

while(window.pollEvent(event) {
    //checking events...
}

My question is, should I use switch statement:

switch(event.type) {
    case sf::Event::Closed:
        window.close();
        break;
    case sf::Event::KeyPressed:
        //...
        break;
}

or if-else statement:

if(event.type == sf::Event::Closed)
    window.close();
else if(event.type == sf::Event::KeyPressed)
    //...

Which is faster in SFML and more readable for others?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...