事件是 SFML.Switch 语句 VS if 语句
我有一些这样的代码:
while(window.pollEvent(event) {
//checking events...
}
我的问题是,我应该使用 switch 语句:
My question is, should I use switch statement:
switch(event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
//...
break;
}
或 if-else 语句:
or if-else statement:
if(event.type == sf::Event::Closed)
window.close();
else if(event.type == sf::Event::KeyPressed)
//...
在 SFML 中哪个更快,对其他人来说更易读?
Which is faster in SFML and more readable for others?
推荐答案
这不是 SFML 的问题,同样的问题可能会出现在其他类型的类似代码中(例如大多数事件循环,有限状态自动机,字节码解释器;另请阅读线程代码).
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).
关于性能,原则上,switch
通常会稍微快一些,但您应该进行基准测试(有些编译器可能优化一系列 if
成 switch
的等价物或相反亦然).在您的情况下,这并不重要(因为大多数时候您的应用程序会 wait 等待 window.pollEvent(event)
中的事件 ....).
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)
....).
假设没有进行大量优化,我会想象一些罕见的开关可能会稍微慢一些,因为例如L1 I-cache 已满,因为热代码太大,等等……但这种情况并不常见.
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.
如果您好奇,请阅读此多路分支代码生成的超优化器分析 关于开关优化的论文(作者 R.Sayle).
If you are curious, read this A Superoptimizer Analysis of Multiway Branch Code Generation paper (by R.Sayle) about switch optimization.
关于可读性,switch
也更具可读性.
Regarding readability, the switch
is a also more readable.
可读性论点似乎与我最相关;将微优化留给编译器,他们做得很好.当然,不要忘记使用 g++ -Wall -O2 -mcpu=native
进行编译,或者将 -O2
替换为 -O3
(以及如果您非常关心性能,甚至可以使用 g++ -flto -O3 -mcpu=native
编译和链接)
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)
(实际上,在这种情况下,可读性是你唯一关心的事情)
如果您想了解编译器优化的方式和原因",请考虑在您的 -O2
标志中添加 -fverbose-asm -S
(然后查看生成的.s
文件)甚至使用 -fdump-tree-all
进行编译(您将获得 数百 个编译器转储文件,对应于各种优化通过一些优化开关(例如 -O2
或 GCC...)代码>-O3代码>).
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
).
相关文章