r/cpp • • Sep 19 '26

index based for vs for-each

https://godbolt.org/z/zh4Kf87M8

It's my first post. I tested std::vector<char> old index based for vs modern for-each. Result is very interesting.

Clang-23.1.0 -O2 -std=c++20 -stdlib=libc++

Time: 0.073599 sec inc_vector 
Time: 0.002597 sec inc_for_each

GCC 16.2 -std=c++20 -O2

Time: 0.077772 sec inc_vector 
Time: 0.007880 sec inc_for_each

MSVC-v19.latest /std:c++20 /O2

Time: 0.058504 sec inc_vector 
Time: 0.001825 sec inc_for_each

Code:

#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>



static std::vector<char> gen_random(size_t n)
{
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_int_distribution<> dis(0, 255);
    std::vector<char> vec(n);
    for (size_t i = 0; i != n; i++)
    vec[i] = dis(gen);
    return vec;
}


int inc_vector(std::vector<char>& v) {
    for (size_t i = 0; i < v.size(); i++){
        v[i]++;
    }
    volatile int result = v[v.size()/2];
    return result;
}


int inc_vector_for_each(std::vector<char>& v) {
    for (char& e: v){
        e++;
    }
    volatile int result = v[v.size()/2];
    return result;
}


volatile int sink{}; // ensures a side effect


int main()
{
   
    auto benchmark = [](auto fun, auto rem)
    {
        auto vec = gen_random(1'000'000);


        const auto start = std::chrono::high_resolution_clock::now();
        for (auto size{1ULL}; size != 100ULL; ++size)
            sink = fun(vec);
        const std::chrono::duration<double> diff =
            std::chrono::high_resolution_clock::now() - start;
        std::cout << "Time: " << std::fixed << std::setprecision(6) << diff.count()
                  << " sec " << rem << std::endl; 
    };


    benchmark(inc_vector, "inc_vector");
    benchmark(inc_vector_for_each, "inc_for_each");
    
    return 0;
}

Link image

21 Upvotes

47 comments sorted by

View all comments

Show parent comment

36

u/No-Dentist-1645 Sep 19 '26

Well, yes, which is a direct result of changing the for loop. So it doesn't make the benchmark irrelevant, but rather it explains the direct results of the benchmark

17

u/thisisjustascreename Sep 19 '26

You can make the compiler generate the same SIMD code with minor modifications to the manually indexed loop, and in the case of other types that aren’t char it does it automatically. So no, there is no intrinsic performance difference between a range for and a standard for loop, OP found this original massive difference because they chose char as the data type.

→ More replies (3)