Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance implication in declaring variables JavaScript

Tags:

javascript

Are there any performance(or otherwise) implications in doing this;

// ...
const greeting = `Hello, ${name}!`;
return greeting;

in comparison to doing just this;

// ...
return `Hello, ${name}!`;
like image 801
John Mutuma Avatar asked Dec 28 '25 19:12

John Mutuma


1 Answers

Yes, assigning a value to a variable name and then returning that variable takes slightly more effort than simply returning the value. For a mini performance test, see:

(warning: the following will block your browser for a bit, depending on your specs)

// references to "name" removed to provide a more minimal test:

const p0 = performance.now();
for (let i = 0; i < 1e9; i++) {
  (() => {
    const greeting = `Hello!`;
    return greeting;
  })();
}
const p1 = performance.now();
for (let i = 0; i < 1e9; i++) {
  (() => {
    return `Hello!`;
  })();
}
const p2 = performance.now();

console.log(p1 - p0);
console.log(p2 - p1);

The difference is quite small, but it's consistently there, at least in V8 - the overhead of the function call mostly overshadows it.

That said, this really sounds like premature optimization - it's probably better to aim for code readability and maintainability, and then fix performance issues if and when they pop up. If declaring a name for the returned value makes the code easier to read, it's probably a good idea to do so, even if it makes the script take a (completely insignificant) longer time to run.

like image 87
CertainPerformance Avatar answered Dec 31 '25 09:12

CertainPerformance