Should one prefer STL algorithms over hand-rolled loops?

后端 未结 11 1439
[愿得一人]
[愿得一人] 2020-12-30 21:29

I seem to be seeing more \'for\' loops over iterators in questions & answers here than I do for_each(), transform(), and the like. Scott Meyers suggests that stl algori

11条回答
  •  再見小時候
    2020-12-30 22:29

    I think the STL algorithm interface is sub-optimal and should be avoided because using the STL toolkit directly (for algorithms) might give a very small gain in performance, but will definitely cost readability, maintainability, and even a bit of writeability when you're learning how to use the tools.

    How much more efficient is a standard for loop over a vector:

    int weighted_sum = 0;
    for (int i = 0; i < a_vector.size(); ++i) {
      weighted_sum += (i + 1) * a_vector[i];  // Just writing something a little nontrivial.
    }
    

    than using a for_each construction, or trying to fit this into a call to accumulate?

    You could argue that the iteration process is less efficient, but a for _ each also introduces a function call at each step (which might be mitigated by trying to inline the function, but remember that "inline" is only a suggestion to the compiler - it may ignore it).

    In any case, the difference is small. In my experience, over 90% of the code you write is not performance critical, but is coder-time critical. By keeping your STL loop all literally inline, it is very readable. There is less indirection to trip over, for yourself or future maintainers. If it's in your style guide, then you're saving some learning time for your coders (admit it, learning to properly use the STL the first time involves a few gotcha moments). This last bit is what I mean by a cost in writeability.

    Of course there are some special cases -- for example, you might actually want that for_each function separated to re-use in several other places. Or, it might be one of those few highly performance-critical sections. But these are special cases -- exceptions rather than the rule.

提交回复
热议问题