哪个更便宜(内存和cpu明智)?
/* caching */
vector<T> vt;
// ... populate the vector
typedef vector<T>::size_type v_t_type ;
vt_type size = vt.size();
for(vt_type i = 0; i < size; ++i)
// ... do stuff with the vector
或者
/* pulling */
for(vt_type i = 0; i < vt.size(); ++i)
// ... do stuff with the vector
不知道缓存和轮询是否是正确的术语,但示例应该是直截了当的。
每次迭代调用 .size() 方法成本高吗?
让我们假设 .size() 做了一些简单的事情,比如从 vt 中读取一个 int 成员变量。
在 PHP 和 Javascript 中,缓存通常比轮询便宜得多。