Avatar ·

Why is element-wise addition in two separate loops much faster than in one combined loop?

Hello, colleagues! I've been writing in C++ for several years, but recently I came across a very strange performance behavior that I can't explain.\n\nI have two arrays: `a` and `b` each of size 20 million elements. I want to first add them element-wise and write the result to array `c`, then add the elements of array `c` to array `d` and write to array `e`. I wrote two code variants: the first one with two separate loops, the second one with one combined loop.\n\nHere's the code:\n\n```cpp\n#include \n#include \n#include \n\nconst size_t N = 20000000;\n\nint main() {\n std::vector a(N, 1);\n std::vector b(N, 2);\n std::vector c(N);\n std::vector d(N, 3);\n std::vector e(N);\n\n // Variant 1: two separate loops