首页 > 解决方案 > 使用什么更快:Array.includes 或 swicth case(在 node.js 中)?

问题描述

背景:

我有一个案例,我需要验证一个变量,它可以在两个有效项数组之一中。这些数组中的每一个都有相当少的项目。

我想到的两种方法是includes在每个数组上使用函数或使用switch/case.

似乎该includes选项比 更干净,switch/case因为我不必手动提及每个case.

恕我直言:从代码管理的角度来看,它也会更正确

问题:

给定数组中的值,使用什么更快includesswitch/case

标签: arraysnode.jsswitch-statement

解决方案


switch/case是比较快的。它的运行速度提高了大约 2.5 倍。

我运行了一些代码moment来计时。执行打印输出以查看它是否正确运行,但在计时步骤中我将它们注释掉。

我检查了第一个数组,第二个数组中的项目,根本没有数组。
每个版本运行 10,000,000 次,结果以毫秒为单位。
它在 MacBook Pro、2.2 GHz Intel Core i7 CPU、16 GB RAM 上运行。

代码:

const moment = require('moment')

const firstItems = [1, 2, 3, 4, 5]
const secondItems = [6, 7, 8, 9, 10]
const testingItems = [1, 6, 10, 11]

const printHere = (here, item) => {
  console.log(`Found it in ${here}: ${item}`)
}

const printNotHere = (item) => {
  console.log(`Could not find it: ${item}`)
}

const printTiming = (start, end) => {
  console.log(`This took: ${end - start}`)
}
const timesToRun = 10000000

const runIncludes = () => {
  testingItems.map(testItem => {
    if (firstItems.includes(testItem)) {
      // printHere('first', testItem)
      return
    }

    if (secondItems.includes(testItem)) {
      // printHere('second', testItem)
      return
    }

    // printNotHere(testItem)
  })
}

const runSwitchCase = () => {
  testingItems.map(testItem => {
    switch (testItem) {
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
        // printHere('first', testItem)
        break

      case 6:
      case 7:
      case 8:
      case 9:
      case 10:
        // printHere('second', testItem)
        break

      default:
        // printNotHere(testItem)
        break
    }
  })
}

console.log('Running includes')
const includesMomentStart = moment()
for (var i = 0; i < timesToRun; i++) {
  runIncludes()
}
printTiming(includesMomentStart, moment())

console.log('Running switch cases')    
const switchCaseMomentStart = moment()
for (var j = 0; j < timesToRun; j++) {
  runSwitchCase()
}
printTiming(switchCaseMomentStart, moment())

结果(三次运行的平均值)是:

Running includes
This took: 2503
Running switch cases
This took: 1082

推荐阅读