2

I was trying to see which methods of converting a string to a number in javascript are more performant, so I went to jsperf to see what might work best. However, I seem to be getting different results based on whether or not the initial variables are defined in the Benchmark.prototype.setup() function, or directly in the global scope.

In the global scope

In Benchmark.prototype.setup

Any ideas on why this might be happening?

1 Answers1

0

This happens because scope lookups come with a small performance penalty.

For example:

var foo = 42; // outer scope
(function() { // inner scope
  doSomething(foo); // needs to look up `foo` and fetch it from the outer scope
}());

Even if you ignore the overhead of the IIFE there, this is still definitely slower than:

var foo = 42;
doSomething(foo); // no scope lookups needed
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248