見代碼和基準這裏:http://jsperf.com/single-vs-multiple-times-2爲什麼運行代碼單的時間比在JavaScript中運行四次慢
我看到在JavaScript中一個奇怪的行爲。單次運行代碼的速度是運行多次的兩倍。以下是代碼:
準備代碼
var MakeKeyCodepoint = function() {};
MakeKeyCodepoint.prototype.makeKey = function(word) {
var len = word.length;
if (len > 255) {
return undefined;
}
var i = len >> 2;
return String.fromCharCode(
(word.charCodeAt(0) & 0x03) << 14 |
(word.charCodeAt(i) & 0x03) << 12 |
(word.charCodeAt(i + i) & 0x03) << 10 |
(word.charCodeAt(i + i + i) & 0x03) << 8 |
len
);
};
var makeKeyCodepointObj = new MakeKeyCodepoint();
運行單一時間
var key = makeKeyCodepointObj.makeKey('www.wired.com');
運行四次
var key = makeKeyCodepointObj.makeKey('www.wired.com');
key = makeKeyCodepointObj.makeKey('www.youtube.com');
key = makeKeyCodepointObj.makeKey('scorecardresearch.com');
key = makeKeyCodepointObj.makeKey('www.google-analytics.com');
我在osx的chrome 34中運行它。
我的結果與OP –
相同我不是在質疑_結果是否如所描述 - 我要求看到它@JonasGrumann。結果被誤讀/曲解了嗎?我發現差異最大爲1%ops/s,瀏覽器摘要顯示與問題相反的趨勢。 – AD7six