Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "use strict" improves performance 10x in this example?

In strict mode, the this context is not forced to be an object. If you call a function on a non-object, this will just be that non-object.

In contrast, in non-strict mode, the this context is always first wrapped in an object if it's not already an object. For example, (42).toString() first wraps 42 in a Number object and then calls Number.prototype.toString with the Number object as this context. In strict mode, the this context is left untouched and just calls Number.prototype.toString with 42 as this context.

(function() {
  console.log(typeof this);
}).call(42); // 'object'

(function() {
  'use strict';
  console.log(typeof this);
}).call(42); // 'number'

In your case, the non-strict mode version spends a lot of time wrapping and unwrapping primitive strings into String object wrappers and back. The strict mode version on the other hand directly works on the primitive string, which improves performance.