0

When we compare something to primitives in functions, are those primitives created and then garbage-collected or browsers do some optimizations on that? It seems such a basic case to me that I wonder if it makes sense to micro-optimize, e.g. assign compared primitive to a variable declared outside the function to avoid repetitive creation of the said primitive?

I often find myself writing:

function isGood(foo) {
    return foo === 'good';
}

Does it make sense to pull out the 'good' out of the function to avoid GC events if any?

var good = 'good';
function isGood(foo) {
    return foo === good;
}
Oleg
  • 9,341
  • 2
  • 43
  • 58
  • ECMA-262 doesn't define *how* implementations do anything, it only describes the observable result, i.e. how they behave. So the only people who can answer this question are those who have access to, and can understand, the source code. – RobG Jun 05 '14 at 22:45
  • Pulling out string literals to only create them once is a standard optimization in every remotely high-level language implementation ever (from C to Python). I'd assume that this code is the least of my worries regarding GC load and go on with my life. –  Jun 06 '14 at 06:54

0 Answers0