[英]Conditional loop: variable vs function?
是否有任何值得選擇的理由,例如性能或安全性?
std::vector<std::string> some_vec{ "a","b","c"};
std::vector<std::string>::const_iterator iter = some_vec.begin();
std::vector<std::string>::const_iterator end = some_vec.end();
while( iter++ != end ){Do}
--
std::vector<std::string> some_vec{ "a","b","c"};
std::vector<std::string>::const_iterator iter = some_vec.begin();
while( iter++ != some_vec.end() ){Do}
第一個依賴於循環過程中end
不會失效:
// some_vec initialised with data!
std::vector<std::string> some_vec;
std::vector<std::string>::const_iterator iter = some_vec.begin();
//std::vector<std::string>::const_iterator end = some_vec.end();
while( iter++ != some_vec.end() ){
if (p(*iter)) iter = some_vec.insert(iter, "foo");
}
insert
可能會使所有迭代器無效,因此不能將end
用於比較。
為了提高效率,我不會太擔心。 如果some_vec.end()
總是返回相同的迭代器,則希望編譯器意識到這一點並執行適當的優化。
首先, while( iter++ != end ){Do}
是錯誤的。 您最終將在循環主體中具有結束迭代器。 解決此問題后,我們可以使用quick-bench.com來查看是否存在性能差異:
#include <vector>
static void test0(benchmark::State& state)
{
std::vector<std::string> some_vec{ "a", "b", "c" };
for (auto _ : state)
{
auto iter = some_vec.cbegin();
auto end = some_vec.cend();
while (iter != end)
{
auto ch = (*iter++)[0];
benchmark::DoNotOptimize(ch);
}
}
benchmark::DoNotOptimize(some_vec);
}
// Register the function as a benchmark
BENCHMARK(test0);
static void test1(benchmark::State& state)
{
// Code before the loop is not measured
std::vector<std::string> some_vec{ "a", "b", "c" };
for (auto _ : state)
{
auto iter = some_vec.cbegin();
while (iter != some_vec.cend())
{
auto ch = (*iter++)[0];
benchmark::DoNotOptimize(ch);
}
}
benchmark::DoNotOptimize(some_vec);
}
BENCHMARK(test1);
沒有優化和gcc 8.2, test0
快1.3倍:
在O3
優化級別下, test0
快1.1倍:
使用Clang 7,它們幾乎相同:
因此,性能似乎不是問題,但是如果最終插入者可以以某種方式失效,則第二個版本更安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.