0

For constants such as string literals used as URLs that might be used multiple times by a function, which has better performance, defining them at module level, or inside the functions where they are used?

Module-level:

const URL = 'http://example.org';
function foo() {
  return URL;
}

Function-level:

function foo() {
  const url = 'http://example.org';
  return url;
}
Ryan Li
  • 9,020
  • 7
  • 33
  • 62

1 Answers1

2

Strings are interned in common engines (definitely for literals at least), so it doesn't make any difference. Just write

function foo() {
  return 'http://example.org';
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Based on the answer you gave, objects are not interned. So in case of general immutable constant objects, would it be better to define them outside the scope of the function? – Ryan Li Jun 27 '18 at 15:59
  • Yes, sharing a single constant object will be better for memory usage than creating a new one in every function call. Whether performance will differ noticeable depends on how the function is used. – Bergi Jun 27 '18 at 16:03
  • There's also the issue of readability and maintainability: With this example, if the URL ever changes, it'd be easier to change it if it's right at the top of your source file, above the function definitions, rather than having to go through your functions looking for the constant. – Zack Jun 27 '18 at 16:41