在for循环中计算向量大小是昂贵的,每次迭代? [英] Is it expensive to compute vector size in for loops, each iteration?
问题描述
c ++编译器是否处理像,建筑是矢量这样的情况:
for(int i = 0; i< ; buildings.size(); i ++){}
在循环中或不是,然后
基于不评估它每次迭代?或者也许我应该自己做,
不是那么漂亮,但:
int n = buildings.size
for(int i = 0; i
buildings.size()
可能会被编译器直接访问向量< ; T>
类。所以你不应该分开对 size
的调用。这种微优化是你不想担心的东西(除非你在一些真正紧密的循环被识别为瓶颈通过分析)。
Does the c++ compiler take care of cases like, buildings is vector:
for (int i = 0; i < buildings.size(); i++) {}
that is, does it notice if buildings is modified in the loop or not, and then based on that not evaluate it each iteration? Or maybe I should do this myself, not that pretty but:
int n = buildings.size();
for (int i = 0; i < n; i++) {}
buildings.size()
will likely be inlined by the compiler to directly access the private size field on the vector<T>
class. So you shouldn't separate the call to size
. This kind of micro-optimization is something you don't want to worry about anyway (unless you're in some really tight loop identified as a bottleneck by profiling).
这篇关于在for循环中计算向量大小是昂贵的,每次迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!