编译器会优化转义内循环吗? [英] Will the compiler optimize escaping an inner loop?

查看:129
本文介绍了编译器会优化转义内循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码我看起来像这样(所有使用done显示):

  bool done = false; 
for(int i = 0; i {
...
for(int j = 0; j< wow; j ++)
{
...
if(foo(i,j))
{
done = true;
break;
}
...
}
if(done)break;
...
}

将任何编译器转换为: / p>

  for(int i = 0; i  {
...
for(int j = 0; j {
...
if(foo(i,j))
goto __done; //与标记的断点相同,如果我们有它
...
}
...
}
__done :;

注意:虽然我最感兴趣的是如果 if(done)break; 被绕过并作为死代码删除,我也感兴趣如果它和 done

解决方案

显然这取决于编译器。当你不确定的最好的事情是查看编译器的汇编输出(所有流行的编译器都有一个开关)。即使你不熟悉程序集,你至少可以将调试版本与优化版本进行比较。



也就是说,这是一个很少有 goto 不是一个坏主意


$ b

在VS2010尝试以下,它确实优化外条件:

  bool done = false; 
for(int i = 0; i <10; i ++)
{
for(int j = 0; j <10; j ++)
{
if(i == 7&& j == 3)
{
done = true;
break;
}
}
if(done)break;
}
return 0;


The code I have looks like this (all uses of done shown):

bool done = false;
for(int i = 0; i < big; i++)
{
  ...
  for(int j = 0; j < wow; j++)
  {
    ...
    if(foo(i,j))
    {
       done = true;
       break;
    }
    ...
  }
  if(done) break;
  ...
}

will any compilers convert it to this:

for(int i = 0; i < big; i++)
{
  ...
  for(int j = 0; j < wow; j++)
  {
    ...
    if(foo(i,j))
      goto __done; // same as a labeled break if we had it
    ...
  }
  ...
}
__done:;

Note: While I'm mostly interested in if the if(done)break; gets bypassed and removed as dead code, I'm also interested in if it and done gets removed altogether.

解决方案

Obviously this depends on the compiler. The best thing to do when you're unsure is to view the compiler's assembly output (all popular compilers have a switch for this). Even if you aren't familiar with assembly, you can at least compare the debug version with the optimized version.

That being said, this is one of the few situations where goto is NOT a bad idea. Feel free to use it to break out of inner loops.

Edit

Just tried the following in VS2010 and it does indeed optimize the outer conditional:

bool done = false;
for(int i = 0; i < 10; i++)
{
    for(int j = 0; j < 10; j++)
    {
        if(i == 7 && j == 3)
        {
            done = true;
            break;
        }
    }
    if(done) break;
}
return 0;

这篇关于编译器会优化转义内循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆