众所周知,在PHP中执行以下操作是个坏主意(因为在每次迭代中都会调用count($array),这会严重降低脚本的执行速度):
for ( $i = 0; $i < count ($array); ++$i )
{
// Code here;
}
相反,应该在循环之外计算条件:
$a = count ($array);
for ( $i = 0; $i < $a; ++$i )
{
// Code here;
}
我是编译语言的新手,所以我遇到了一个问题:
相同的规则是否适用于例如C和C之类的编译语言?
假设我要在C中迭代vector.我应该避免这样的for循环吗?
for ( int i = 0; i < vector.size(); ++i )
{
// Code here
}
如果这不是编译语言中的问题,那是因为编译器会注意这一点并优化可执行文件,还是背后还有其他原因?
解决方法:
问题归结为“编译器在编译时知道答案”吗?
如果您给出了答案,答案是“否”.由于可以在循环内更改向量的大小,因此每次都应对其进行评估(但它非常快,因为它一次不会计数一次).
像这样的代码:
int myArray[20];
for(int ii = 0; ii < sizeof(myArray)/sizeof(*myArray); ii++) {
实际上将在编译时评估sizeof,因此效率稍高.注意-您需要整个表达式,因为在这种情况下sizeof(myArray)本身将返回80(其中int为四个字节).使用sizeof(* myArray)的优点是,如果您对myArray的类型改变主意,那么这行代码不会中断……
而且您在这里使用除法的事实并不会减慢执行速度,因为它都是在编译时完成的(仅一次).
再重申一下我在评论中所说的话:在这种情况下,您建议的版本在评估每次迭代的向量大小的同时,实际上不是问题.除了最紧密的循环外,您几乎不可能看到所有性能都有差异.不要掉入the trap of micro-optimization
这是一个简单的计时示例:
#include
#include
#include
using namespace std;
int main(void) {
vector testVector(200);
int ii, jj;
register int ss;
time_t startT, endT;
// case 1: using a constant for loop condition
startT = clock();
for(ii = 0; ii < 100000; ii++) {
for(jj = 0; jj < 200; jj++) {
testVector[jj] = ii - jj;
}
}
endT = clock();
printf("using constant: elapsed time: %.2f ms\n", (endT - startT) * 1000.0 / CLOCKS_PER_SEC);
// case 2: using size():
startT = clock();
for(ii = 0; ii < 100000; ii++) {
for(jj = 0; jj < testVector.size(); jj++) {
testVector[jj] = ii - jj;
}
}
endT = clock();
printf("using size: elapsed time: %.2f ms\n", (endT - startT) * 1000.0 / CLOCKS_PER_SEC);
// case 3: single call to size():
startT = clock();
ss = testVector.size();
for(ii = 0; ii < 100000; ii++) {
for(jj = 0; jj < ss; jj++) {
testVector[jj] = ii - jj;
}
}
endT = clock();
printf("with size out of loop: elapsed time: %.2f ms\n", (endT - startT) * 1000.0 / CLOCKS_PER_SEC);
}
得到以下结果:
using constant: elapsed time: 162.47 ms
using size: elapsed time: 277.02 ms
with size out of loop: elapsed time: 241.01 ms
如您所见,在每个循环中查找向量的大小都存在有限的时间.但是20,000,000个呼叫大约需要100毫秒,每个呼叫大约需要5 ns.听起来不错;如您所见,当循环足够紧时,它是可测量的;但是在大多数“真实”代码实例中(在循环中您可能会做更多的事情),这不太可能具有实际意义.正如您还看到的那样,仅将对size的调用移出循环并没有多大帮助-使用常量与变量的区别更大.
标签:performance,for-loop,c-4,php
来源: https://codeday.me/bug/20191030/1964792.html