all: I have two pieces of code. The first one is:
#include <iostream>
using namespace std;
static constexpr long long n = 1000000000;
int main() {
int sum = 0;
int* a = new int[n];
int* b = new int[n];
for (long long i=0; i<n; i++) {
a[i] = static_cast<int>(i);
}
for (long long i=0; i<n; i++) {
sum *= a[i];
sum += a[i];
}
for (long long i=0; i<n; i++) {
b[i] = static_cast<int>(i);
}
for (long long i=0; i<n; i++) {
sum *= b[i];
sum += b[i];
}
cout<<sum<<endl;
}
The second one is:
#include <iostream>
using namespace std;
constexpr long long n = 1000000000;
int main() {
int* a = new int[n];
int* b = new int[n];
int sum = 0;
for (long long i=0; i<n; i++) {
a[i] = static_cast<int>(i);
b[i] = static_cast<int>(i);
}
for (long long i=0; i<n; i++) {
sum *= a[i];
sum += a[i];
sum *= b[i];
sum += b[i];
}
cout<<sum<<endl;
}
I think the first programs should be much faster than the second one, since it's more cache friendly. However, the truth is the second one is a litter faster. On my server, the first one takes 23s while the second one takes 20s, can some one explain this?