Static Arrays using std::array

Passing Arrays by Reference

Why is it more efficient to pass a std::array by reference to a function instead of by value?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved