什么是最有效的循环边界检查 [英] What is the most efficent for loop bounds checking

查看:249
本文介绍了什么是最有效的循环边界检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个for循环实现应该运行得更快或者它们相等?

Of the two following for loop implementations which should run faster or are they equal?

这一个:

for(int i=0; i<objectPtr->bound; i++){

//do something that has no affect on objectPtr->bound

}

或这一个:

int myBound = objectPtr->bound;

for(int i=0; i<myBound; i++){
//do something that has no effect on objectPtr->bound or myBound
}

我的预感是后者更快,但可能有一部分编译过程,我不明白使它们的速度相等。我认为前者将必须做一个地址解析每个循环周期来确定该值是否已经改变。

My hunch is the latter is faster but there could be some part of the compilation process that I don't understand that makes them equal in speed. I think the former will have to do an address resolution each loop cycle to determine if the value has changed.

有一些c ++语法可以用来让编译器知道值/ bound不会改变。我知道volatile让编译器知道该值总是有可能改变,所以我可以使用const int为objectPtr-> bound变量,让编译器不总是检查其值每个循环迭代?

Is there some c++ syntax that can be used to let the compiler know that the value/bound will not change. I know volatile lets the compiler know that the value will always have the possibility of changing so could I use const int for the objectPtr->bound variable to get the compiler to not always check its value each loop iteration?

推荐答案

编译器可能会看到 objectPtr-> bound 的值不会在迭代。在这种情况下,它会自动将它提取到一个变量,以避免重复查找。

The compiler might see that the value of objectPtr->bound doesn't change between iterations. In this case, it will automatically extract it into a variable to avoid repeated lookups.

没有办法显式告诉编译器表达式的值不更改。

There is no way to explicitly tell the compiler that the value of an expression doesn't change. If the compiler can't detect it itself, you can copy the value into a variable as you did.

将局部变量声明为 const

Declaring local variables as const is not necessary. The compiler can see that you don't assign to the variable in a loop and deduce that its value doesn't change.

这篇关于什么是最有效的循环边界检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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