什么是根据效率编写循环的最佳方法: 方式)我应该优化还是让编译器来做这件事?
/*here I'm hoping that compiler will optimize this
code and won't be calling size every time it iterates through this loop*/
for (unsigned i = firstString.size(); i < anotherString.size(), ++i)
{
//do something
}
或者也许我应该做这种方式: 路B)
unsigned first = firstString.size();
unsigned second = anotherString.size();
,现在我可以写:
for (unsigned i = first; i < second, ++i)
{
//do something
}
第二条路我看来,像更坏的选择,原因有二:污染范围和详细程度,但它公顷这是确保每个对象调用size()一次的好处。
期待您的回答。
请注意'firstString.size()'只会调用一次,所以不值得将它移出循环。 – 2010-05-16 17:02:25
或者你可以使用迭代器并完全避免这个问题。 – 2010-05-16 19:21:57
请勿使用“无符号”;不能保证“std :: size_t”将与所有平台上的无符号相同(例如,它可以是“无符号长整数”)。相反,使用“std :: size_t”。 – 2010-05-17 03:05:58