gpt4 book ai didi

javascript - for 循环中的 if 条件 - 性能差异

转载 作者:行者123 更新时间:2023-12-03 06:58:09 25 4
gpt4 key购买 nike

条件1

for( var i = 0; i < 1000; i++ ) {
if( i != 0 ) {
console.log("i is not zero.!");
} else {
console.log("i is zero.!");
}
}

条件2

for( var i = 0; i < 1000; i++ ) {
if( i == 0 ) {
console.log("i is zero.!");
} else {
console.log("i is not zero.!");
}
}
  1. 哪种方法更可取(我的意思是更合适)?

  2. 这两者之间有性能差异吗?

最佳答案

尝试一下!

还有另一种方法可以做到这一点:

console.log( i==0 ? "i is zero.!" : ""i is not zero.! );

有一个小长凳:

function run(e) {
var start=1*new Date();
var loop=loopcnt.value;
if (e.target.id=="==") {
for( var i = 0; i < loop; i++ ) {
if( i == 0 ) {
var log="i is zero.!";
} else {
var log="i is not zero.!";
}
}
} else if (e.target.id=="!=") {
for( var i = 0; i < loop; i++ ) {
if( i != 0 ) {
var log="i is not zero.!";
} else {
var log="i is zero.!";
}
}
} else if (e.target.id=="(=") {
for( var i = 0; i < loop; i++ ) {
var log=i==0?"i is zero.!":"i is not zero.!";
}
} else {
for( var i = 0; i < loop; i++ ) {
var log=i!=0?"i is not zero.!":"i is zero.!";
}
};
elapsed.innerHTML=(1*new Date()-start).toFixed(0)+"ms."
}
body,button,input{font-family:sans;font-size:8pt;padding:0pt}div{font-size:12pt;}
Loop: <input id=loopcnt value="3000000" size="8" />
<button id="==" onclick="run(event)">if == {} else {}</button>
<button id="!=" onclick="run(event)">if != {} else {}</button>
<button id="(=" onclick="run(event)">( == ? "" : "" )</button>
<button id="(!" onclick="run(event)">( != ? "" : "" )</button>
<div id="elapsed"></div>

通过使用firefoxchrome,没有明显的区别,但是Spidermonkey使用似乎做得更快一些! = 比使用 ==:

time smjs <<<'
for( var i = 0; i < 10000000; i++ ) {
if ( i == 0 ) { var log="i is zero.!"; }
else { var log="i is not zero.!"; } } '
real 0m0.054s
user 0m0.044s
sys 0m0.004s

time smjs <<<'
for( var i = 0; i < 10000000; i++ ) {
if ( i != 0 ) { var log="i is not zero.!"; }
else { var log="i is zero.!"; } } '
real 0m0.043s
user 0m0.040s
sys 0m0.000s

time smjs <<<'
for( var i = 0; i < 10000000; i++ ) {
var log=(i==0?"i is zero.!":"i is not zero.!"); } '
real 0m0.051s
user 0m0.048s
sys 0m0.000s


time smjs <<<'
for( var i = 0; i < 10000000; i++ ) {
var log=(i!=0?"i is not zero.!":"i is zero.!"); } '
real 0m0.049s
user 0m0.040s
sys 0m0.008s

但这还没有经过充分测试(在真正免费的主机上,通过进行大量测试和完整统计)。

关于javascript - for 循环中的 if 条件 - 性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37180334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com