问题描述
查看jQuery核心,我发现了以下代码约定:
Looking in the jQuery core I found the following code convention:
nth: function(elem, i, match){
return match[3] - 0 === i;
},
我对片段匹配感到非常好奇[3] - 0
在谷歌上搜索'-0'并不是太高效,搜索'减零'带回鲍勃迪伦歌曲的参考。
Hunting around for '-0' on google isn't too productive, and a search for 'minus zero' brings back a reference to a Bob Dylan song.
所以,任何人都可以告诉我。这是某种性能技巧,还是有理由这样做而不是 parseInt
或 parseFloat
?
So, can anyone tell me. Is this some sort of performance trick, or is there a reason for doing this rather than a parseInt
or parseFloat
?
推荐答案
更新:
我的快速而肮脏的基准测试并不是很有用,因为它只是在循环中转换字符串1234。我再次尝试使用随机数字列表,结果遍布地图。这台计算机上的三种方法都在400-500毫秒内,除非它们跳到1300毫秒!我认为垃圾收集正在干扰。下面是一些在Firebug中使用的代码,以防我做了一些愚蠢的事情:
My "quick and dirty" benchmark was not very useful because it was just converting the string "1234" in a loop. I tried again using a random list of numbers, and the results are all over the map. The three methods are all within 400-500 ms on this computer except when they jump to 1300 ms! I think garbage collection is interfering. Here is some code to play with in Firebug, in case I did something stupid:
function randomList() {
var list = [];
for (var i = 0; i < 1000000; i++) {
list.push("" + Math.floor(Math.random()*4000000000));
}
return list;
}
function testParseInt(list) {
console.log("Sanity check: parseInt('" + list[0] + "') = " + parseInt(list[0]) );
var start = new Date();
for (var string in list)
var tmp = parseInt(string);
var time = new Date() - start;
console.log("parseInt(string): " + time);
}
function testMinusZero(list) {
console.log("Sanity check: '" + list[0] + "' - 0 = " + (list[0] - 0));
var start = new Date();
for (var string in list)
var tmp = string - 0;
var time = new Date() - start;
console.log("string - 0: " + time);
}
function testUnaryPlus(list) {
console.log("Sanity check: +'" + list[0] + "' = " + (+list[0]));
var start = new Date();
for (var string in list)
var tmp = +string;
var time = new Date() - start;
console.log("+string: " + time);
}
function testPlusZero(list) {
console.log("Sanity check: '" + list[0] + "' + 0 = " + (list[0] + 0) + " Oh no!");
var start = new Date();
for (var string in list)
var tmp = string + 0;
var time = new Date() - start;
console.log("string + 0: " + time);
}
var numbers = randomList();
testParseInt(numbers);
testMinusZero(numbers);
testUnaryPlus(numbers);
testPlusZero(numbers);
这篇关于是否将某种JavaScript性能技巧归结为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!