c ++ for循环优化问题 [英] c++ for loop optimization question

查看:198
本文介绍了c ++ for循环优化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VC ++中有以下代码:

I have the following looking code in VC++:

for (int i = (a - 1) * b; i < a * b && i < someObject->someFunction(); i++)
{
    // ...
}

据我所知,编译器优化所有这些算术运算,它们不会在每个循环执行,但我不知道他们可以告诉上面的函数每次都返回相同的值,并且不需要每次都调用。

As far as I know compilers optimize all these arithmetic operations and they won't be executed on each loop, but I'm not sure if they can tell that the function above also returns the same value each time and it doesn't need to be called each time.

这是一个更好的做法,保存所有的计算或者只是依靠编译器优化来获得更可读的代码?

Is it a better practice to save all calculations into variables, or just rely on compiler optimizations to have a more readable code?

int start = (a - 1) * b;
int expra = a * b;
int exprb = someObject->someFunction();
for (int i = startl i < expra && i < exprb; i++)
{
    // ...
}


推荐答案

如果一个函数驻留在与其调用者相同的编译单元中,推导出关于它的一些事实 - 例如它的输出可能不会为随后的调用而改变。

If a function resides within the same compilation unit as its caller, the compiler can often deduce some facts about it - e.g. that its output might not change for subsequent calls. In general, however, that is not the case.

在您的示例中,为这些简单的算术表达式分配变量并不会改变生成的目标代码的任何内容, ,在我看来,使代码更不可读。除非你有一堆长表达式,不能合理地放在一两行内,你应该避免使用临时变量 - 如果没有其他原因,那么只是为了减少命名空间污染。

In your example, assigning variables for these simple arithmetic expressions does not really change anything with regards to the produced object code and, in my opinion, makes the code less readable. Unless you have a bunch of long expressions that cannot reasonably be put within a line or two, you should avoid using temporary variables - if for no other reason, then just to reduce namespace pollution.

使用临时变量意味着程序员需要很大的管理开销,以便保持它们分离并避免意外的副作用。

Using temporary variables implies a significant management overhead for the programmer, in order to keep them separate and avoid unintended side-effects. It also makes reusing code snippets harder.

另一方面,将函数的结果分配给变量可以帮助编译器通过显式避免多个函数来更好地优化代码

On the other hand, assigning the result of the function to a variable can help the compiler optimise your code better by explicitly avoiding multiple function calls.

个人而言,我会这样做:

Personally, I would go with this:

int expr = someObject->someFunction();
for (int i = (a - 1) * b; i < a * b && i < expr; i++)
{
    // ...
}

这篇关于c ++ for循环优化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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