I have found many people saying that passing a primitive value, such as an int, by value, is faster than passing by reference.
However, I wrote the code below, and passing by value, and it averages 2 second run time.
#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
int func(unsigned long long x) {
++x;
return x;
}
int main()
{
for (int b = 0; b < 5; b++) {
unsigned long long x = 0;
auto start = high_resolution_clock::now();
for (long long j = 0; j < 500000; j++) {
for (long long i = 0; i < 180000000; i++) {
x = func(x);
}
}
auto stop = high_resolution_clock::now();
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
cout << x <<" iterations took " << microseconds << " microseconds\n";
}
}
Then when I pass by reference, it averages less than 1 microsecond.
#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
void func(unsigned long long& x) {
++x;
}
int main()
{
for (int b = 0; b < 5; b++) {
unsigned long long x = 0;
auto start = high_resolution_clock::now();
for (long long j = 0; j < 500000; j++) {
for (long long i = 0; i < 180000000; i++) {
func(x);
}
}
auto stop = high_resolution_clock::now();
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
cout << x <<" Took " << microseconds << " microseconds\n";
}
}
I would like an explanation to why this happens please.
Disclaimer: I am fairly new to C++