JS: Should massive arrays only used by one function be created inside or out?

Viewed 44

In a piece of code I'm reading there is a function roughly as follows:

const toColor = (name) => {
  const colors = [
    colorHash,
    colorHash,
    colorHash // many more colors
  ];

  // some simple actions to get a color from the given name
  
  return color;
};

The colors array is quite massive and the function is being called a lot. My understanding is that this array is therefore created anew every time the function is called. Is it good practice to move this array outside of the function and just have it persist there, or is the performance impact of recreating the array per function call insignificant?

1 Answers

Any data that doesn't change per execution of the function should be stored outside of the function.

The same applies when talking about loops for the same reasons.

Related