If-Else
与 Switch
语句// 第一种状况 if (x === 0) { console.log(0); } else if (x === 1) { console.log(1); } switch (x) { case 0: console.log(0); break; case 1: console.log(1); break; } // 第二种状况 if (x === 0) { console.log(0); } else if (x === 1) { console.log(1); } else if (x === 2) { console.log(2); } else if (x === 3) { console.log(3); } else if (x === 4) { console.log(4); } else if (x === 5) { console.log(5); } else if (x === 6) { console.log(6); } else if (x === 7) { console.log(7); } else if (x === 8) { console.log(8); } else if (x === 9) { console.log(9); } switch (x) { case 0: console.log(0); break; case 1: console.log(1); break; case 2: console.log(2); break; case 3: console.log(3); break; case 4: console.log(4); break; case 5: console.log(5); break; case 6: console.log(6); break; case 7: console.log(7); break; case 8: console.log(8); break; case 9: console.log(9); break; }
咱们来看上面两个例子大多数的人都觉的 if
语句在条件较少的时候要比 switch
清晰,若是条件较多那么就是使用 switch
更加清晰明了,事实上 switch
语句较 if
语句相比较具备更高的效率。固然这种效率性能的提高只能在分支
条件较多较为复杂的时候体现出来,这与咱们的直觉同样 条件较多的时候使用 switch
语句。javascript
If-Else
语句另一种减小条件判断数量的方法是将 if-else
组织成一系列嵌套的 if-else
表达式。使用一个单独的一长
串的 if-else
一般致使运行缓慢,由于每一个条件体都要被计算。java
if (x < 3) { if (x === 0) {} else if (x === 1) {} else if (x === 2) {} } else if (x < 6) { if (x === 3) {} else if (x === 4) {} else if (x === 5) {} } else if (x < 9) { if (x === 6) {} else if (x === 7) {} else if (x === 8) {} }
在重写的 if-else
表达式中,每次抵达正确分支时最多经过四个条件判断。它使用二分搜索法将值域分红
了一系列区间,而后逐步缩小范围。当数值范围分布在 0 到 9 时,此代码的平均运行时间大约是前面那
个版的一半。此方法适用于须要测试大量数值的状况 (相对离散值来讲 switch
语句更合适)。数组
有些状况下要避免使用 if-else
或 switch
。当有大量离散值须要测试时,if-else
和 switch
都比使用查表法
要慢得多。在 JavaScript 中查表法可以使用数组或者普通对象实现,查表法访问数据比 if-else
或者 switch
更快,
特别当条件体的数目很大时。性能
let map = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(map[x]);