Why does element-wise addition in two separate loops work faster than in one combined loop?
Hi everyone! I've been writing in C++ for a couple of months, and I encountered very strange performance behavior. There are two arrays: `a` and `b` of size 200000000 elements (about 800 MB each). I want to add them element-wise and store the result in array `c`, then multiply each element of `c` by 2 and store in `d`.
I wrote two code variants:
**Variant 1 (two separate loops):**
```cpp
for (int i = 0; i < n; ++i) {
c[i] = a[i] + b[i];
}
for (int i = 0; i < n; ++i) {
d[i] = c[i] * 2;
}
```
**Variant 2 (one combined loop):**
```cpp
for (int i = 0; i < n; ++i) {
c[i] = a[i] + b[i];
d[i] = c[i] * 2;
}
```
I expected the second variant to be faster since it does everything in one pass. But in practice (MSVC compiler, /O2 flags, x64 architecture) the first
No answers yet.
Log in to leave an answer