高性能的 JavaScript -- 流程掌握

高机能的 JavaScript — 流程掌握

If-ElseSwitch 语句

// 第一种状况
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 语句

优化 If-Else 语句

别的一种削减前提推断数量的要领是将 if-else 组织成一系列嵌套的 if-else 表达式。运用一个零丁的一长
串的 if-else 一般致使运转迟缓,由于每一个前提体都要被盘算。

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-elseswitch。当有大批离散值须要测试时,if-elseswitch 都比运用查表法
要慢很多。在 JavaScript 中查表法可运用数组或许一般对象完成,查表法接见数据比 if-else 或许 switch 更快,
特别当前提体的数量很大时。

let map = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(map[x]);
    原文作者:pkeros
    原文地址: https://segmentfault.com/a/1190000009350592
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞