Use these C++ loops to make your code faster

preview_player
Показать описание
There are many different C++ for loops. Learn which one is the fastest and how to avoid common mistakes.
I show different alternatives including range-based for loops and standard algorithms. Afterwards, those for loops are benchmarked against each other.

00:00 Intro
00:30 The task
01:33 The classic loop
04:19 The iterator loop
06:10 The range based loop
07:47 Standard algorithms
10:35 The comparison

Tools that I use:

In code:
Рекомендации по теме
Комментарии
Автор

Really great video! Thorough and understandable explanations for why certain implementations are good/bad. Please make more content like this!! <3

_FLOROID_
Автор

Fun fact: They usually generate the exact same machine code at -O2. No difference at all. The compiler does the optimization part. Also ++i is not faster than i++ in for loops since modern compilers are smart and they implicitly turn i++ into ++i without letting you know. The only one that could be faster is the parallel one. The rest are equivalent in terms of efficiency. Also pass by reference is usually less efficient for small types such as double. Pass them by value (copy) like const auto element instead of const auto& element.

ohwow
Автор

Thank you, that was very insightful
One question regarding vector.size()

shouldnt it it be better (performance-wise) if we calculate it before the for loop, and not inside?
i.e
std::size_t sizeVector = someVector.size()
for(size_t idx=0; ; ++idx)

thanks again for your time and effort

Account-ficu
Автор

Hi
Is it safe to apply += operator (or any nonatomic operator) on the same operand from a parallel foreach?
I got weird sum result there. (Algorithm.hpp line 29)
Maybe std::reduce is better choice with par.

My results:
1.63823e+07 regular_for_loop 8918usec
1.63823e+07 bad_regular_for_loop 8893usec
1.63823e+07 iterator_loop 8903usec
1.63823e+07 bad_iterator_loop 8605usec
1.63823e+07 range_based_loop 8558usec
1.63823e+07 std_accumulate 8604usec
1.63823e+07 std_reduce_parallel-cpp20 6499usec
3.01759e+06 parallel_foreach_loop 10308usec

msvc
release build, optimization yes (favor speed /O2)

danielkarpati
Автор

That's how you save some time, right there!

stefcozum
Автор

Shouldn't always the parallel one be much faster?

jarfallafamiljetandlakarna