Passing Arrays by Reference
Why is it more efficient to pass a std::array by reference to a function instead of by value?
When you pass a std::array by value to a function, the entire array is copied. This means that all the elements in the array are copied into a new array, which is then passed to the function. For large arrays, this can be inefficient in terms of both memory usage and performance.
On the other hand, when you pass a std::array by reference, no copying occurs. Instead, the function receives a reference to the original array. This is much more efficient, as it avoids the overhead of copying all the elements.
Here's an example:
#include <array>
void ByValue(std::array<int, 1000> arr) {
// ...
}
void ByReference(std::array<int, 1000>& arr) {
// ...
}
int main() {
std::array<int, 1000> BigArray{};
// Makes a copy of 1000 integers
ByValue(BigArray);
//No copying occurs
ByReference(BigArray);
}In the PrintArrayByValue function, the entire BigArray is copied when it's passed to the function. This involves copying 1000 integers.
In the PrintArrayByReference function, BigArray is passed by const reference. No copying occurs, and the function can access the array through the reference.
Therefore, prefer passing std::array by reference when you don't need to modify the array, or by const reference when you don't need to modify the array and you want to guarantee that the function won't change it.
Static Arrays using std::array
An introduction to static arrays using std::array - an object that can store a collection of other objects