Skip to content

Instantly share code, notes, and snippets.

@gaogao-9
Last active October 28, 2015 16:12
Show Gist options
  • Save gaogao-9/ad2d24c03f3041f6c129 to your computer and use it in GitHub Desktop.
Save gaogao-9/ad2d24c03f3041f6c129 to your computer and use it in GitHub Desktop.
速度比較
(function(){
var i,flag,res,times = 1000000;
console.time("rand");
res = 0;
for(i=0;i<times;++i){
flag = ["","true"][Math.random()*2|0];
if(flag){
res += Math.random();
}
}
console.log(res);
console.timeEnd("rand");
console.time("rand -> 0or1");
res = 0;
for(i=0;i<times;++i){
flag = ["","true"][Math.random()*2|0];
if(flag ? 1 : 0){
res += Math.random();
}
}
console.log(res);
console.timeEnd("rand -> 0or1");
})();
(function(){
var i,flag,res,times = 1000000;
console.time("rand -> 0or1");
res = 0;
for(i=0;i<times;++i){
flag = ["","true"][Math.random()*2|0];
if(flag ? 1 : 0){
res += Math.random();
}
}
console.log(res);
console.timeEnd("rand -> 0or1");
console.time("rand");
res = 0;
for(i=0;i<times;++i){
flag = ["","true"][Math.random()*2|0];
if(flag){
res += Math.random();
}
}
console.log(res);
console.timeEnd("rand");
})();
(1) randが先
250115.31135154935
rand: 421.314ms
249348.21210631728
rand -> 0or1: 385.660ms
(2) randが後
250007.9748392962
rand -> 0or1: 429.586ms
249859.1769272962
rand: 390.860ms
結論
・後出しが有利であって、両者に差異はない。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment