亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

高性能的 JavaScript -- 流程控制

Mike617 / 2194人閱讀

摘要:高性能的流程控制與語句第一種情況第二種情況我們來看上面兩個(gè)例子大多數(shù)的人都覺的語句在條件較少的時(shí)候要比清晰,如果條件較多那么就是使用更加清晰明了,事實(shí)上語句較語句相比較具有更高的效率。

高性能的 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;
}

我們來看上面兩個(gè)例子大多數(shù)的人都覺的 if 語句在條件較少的時(shí)候要比 switch 清晰,如果條件較多那么就是使用
switch 更加清晰明了,事實(shí)上 switch 語句較 if 語句相比較具有更高的效率。當(dāng)然這種效率性能的提升只能在分支
條件較多較為復(fù)雜的時(shí)候體現(xiàn)出來,這與我們的直覺一樣 條件較多的時(shí)候使用 switch 語句。

優(yōu)化 If-Else 語句

另外一種減少條件判斷數(shù)量的方法是將 if-else 組織成一系列嵌套的 if-else 表達(dá)式。使用一個(gè)多帶帶的一長(zhǎng)
串的 if-else 通常導(dǎo)致運(yùn)行緩慢,因?yàn)槊總€(gè)條件體都要被計(jì)算。

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 表達(dá)式中,每次抵達(dá)正確分支時(shí)最多通過四個(gè)條件判斷。它使用二分搜索法將值域分成
了一系列區(qū)間,然后逐步縮小范圍。當(dāng)數(shù)值范圍分布在 0 到 9 時(shí),此代碼的平均運(yùn)行時(shí)間大約是前面那
個(gè)版的一半。此方法適用于需要測(cè)試大量數(shù)值的情況 (相對(duì)離散值來說 switch 語句更合適)。

表查法

有些情況下要避免使用 if-elseswitch。當(dāng)有大量離散值需要測(cè)試時(shí),if-elseswitch 都比使用查表法
要慢得多。在 JavaScript 中查表法可使用數(shù)組或者普通對(duì)象實(shí)現(xiàn),查表法訪問數(shù)據(jù)比 if-else 或者 switch 更快,
特別當(dāng)條件體的數(shù)目很大時(shí)。

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

console.log(map[x]);

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/82911.html

Failed to recv the data from server completely (SIZE:0/8, REASON:closed)