哪一个性能更好,为什么?谢谢你帮助我
if(x==="abc" || x ==="def" || x==="ghi" || x==="jkl"){
//logic
}
if(["abc","def","ghi","jkl"].includes(x)){
//logic
}
最佳答案
小数组上没有区别 也许它在更大的数组上会有所不同
var loop = 1000000;
var total1 = 0;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
for(var i = 0; i < loop; i++)
{
var x = ["abc","def","ghi","jkl", "aze", ][getRandomInt(0,3)];
var a = new Date().getTime();
if(x==="abc" || x ==="def" || x==="ghi" || x==="jkl"){
var b = new Date().getTime();
total1 += (b-a);
}
else {
var b = new Date().getTime();
total1 += (b-a);
}
}
var total2 = 0;
for(var i = 0; i < loop; i++)
{
var x = ["abc","def","ghi","jkl"][getRandomInt(0,3)]
var a = new Date().getTime();
if(["abc","def","ghi","jkl"].includes(x)){
var b = new Date().getTime();
total2 += (b-a);
}
else{
var b = new Date().getTime();
total2 += (b-a);
}
}
console.log("=> total1 "+(total1/loop));
console.log("=> total2 "+(total2/loop));
关于JavaScript || (或)条件具有更好的性能或包括?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65625452/