Why does "use strict" increase productivity 10 times in this example?



  • After question https://ru.stackoverflow.com/questions/547482/ I was wondering why a simple addition. "use strict" Method String.prototype increases productivity 10 times. https://ru.stackoverflow.com/a/547483/7575 , https://stackoverflow.com/users/1048572/bergi too short and incomprehensible.

    Why is this sharp difference in productivity between two almost identical methods, the only difference between which is only "use strict" early? Can you explain the details and the rationale?

      
    

    String.prototype.count = function(char) {
    var n = 0;
    for (var i = 0; i < this.length; i++)
    if (this[i] == char) n++;
    return n;
    };

    String.prototype.count_strict = function(char) {
    "use strict";
    var n = 0;
    for (var i = 0; i < this.length; i++)
    if (this[i] == char) n++;
    return n;
    };
    // Here is how I measued speed, using Node.js 6.1.0

    var STR = '0110101110010110100111010011101010101111110001010110010101011101101010101010111111000';
    var REP = 1e4;

    console.time('proto');
    for (var i = 0; i < REP; i++) STR.count('1');
    console.timeEnd('proto');

    console.time('proto-strict');
    for (var i = 0; i < REP; i++) STR.count_strict('1');
    console.timeEnd('proto-strict');

    Result:

    proto: 101 ms
    proto-strict: 7.5 ms

    Translation of question https://stackoverflow.com/questions/38411552/ ” https://stackoverflow.com/users/1968972/exebook ♪



  • https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Strict_mode#Securing_JavaScript ♪ If you call a function for an object, this I'm not gonna be the target.

    And on the contrary, not strict. this The context always turns into an object at first if it's not an object. For example, (42).toString() First of all, 42 facility NumberAnd then he does. Number.prototype.toStringobject Number in the context this♪ In strict context this remains untouched and just called Number.prototype.toString c 42 in the context this

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

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

    In your case, the unsuccessful version of the regime spends a lot of time on the transfer and disengagement of the primitive. string Total String and back. On the other hand, the strict regime directly works with the primitive. stringwhich increases productivity.

    Translation of response https://stackoverflow.com/questions/38411552/ ” https://stackoverflow.com/users/1321716/mattias-buelens ♪




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2