이 예제에서“엄격한 사용”이 성능 10 배를 향상시키는 이유는 무엇입니까?
질문 Stringing.prototype 성능 확장 질문에 따라 메서드에 추가 "use strict"
하는 것만으로 String.prototype
성능이 10 배 향상 되었기 때문에 정말 흥미 롭습니다 . 설명 에 의해 BERGI은 짧고 나에게 그것을 설명하지 않습니다. 왜 거의 동일한 두 가지 방법 사이에 극적인 차이가 "use strict"
있습니까? 이것에 대한 이론과 더 자세하게 설명 할 수 있습니까?
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');
결과:
proto: 101 ms
proto-strict: 7.5 ms
엄격 모드에서는 this
컨텍스트가 객체가 될 수 없습니다. 객체가 아닌 객체에서 함수를 호출하면 this
해당 객체가 아닙니다.
반대로, 엄격하지 않은 모드에서는 this
컨텍스트가 아직 오브젝트가 아닌 경우 항상 오브젝트에 랩핑됩니다. 예를 들어, (42).toString()
제 랩 42
A의 Number
다음 개체 및 호출 Number.prototype.toString
와 Number
같은 오브젝트 this
컨텍스트. 엄격 모드에서는 this
컨텍스트가 그대로 유지되고 컨텍스트 로 호출 Number.prototype.toString
됩니다 .42
this
(function() {
console.log(typeof this);
}).call(42); // 'object'
(function() {
'use strict';
console.log(typeof this);
}).call(42); // 'number'
귀하의 경우, 비 엄격 모드 버전은 시간 포장 및 원시 풀기를 많이 소비 string
에들 String
객체 래퍼와 다시. 반면 엄격 모드 버전은 프리미티브 string
에서 직접 작동하여 성능을 향상시킵니다.
참고 URL : https://stackoverflow.com/questions/38411552/why-use-strict-improves-performance-10x-in-this-example
'IT' 카테고리의 다른 글
Guice에서 바인딩 재정의 (0) | 2020.07.04 |
---|---|
git push -u origin master에서 -u 플래그는 무엇을 의미합니까? (0) | 2020.07.04 |
Xcode 4-콘솔 / 로그 창 분리 (0) | 2020.07.04 |
Ruby가 i ++ 또는 i-(증가 / 감소 연산자)를 지원하지 않는 이유는 무엇입니까? (0) | 2020.07.04 |
C ++에 비해 D는 얼마나 빠릅니까? (0) | 2020.07.04 |