arrays - 使用什么更快:Array.includes 或 swicth case(在 node.js 中)?
问题描述
背景:
我有一个案例,我需要验证一个变量,它可以在两个有效项数组之一中。这些数组中的每一个都有相当少的项目。
我想到的两种方法是includes
在每个数组上使用函数或使用switch/case
.
似乎该includes
选项比 更干净,switch/case
因为我不必手动提及每个case
.
恕我直言:从代码管理的角度来看,它也会更正确
问题:
给定数组中的值,使用什么更快:includes
或switch/case
?
解决方案
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
推荐阅读
- bash - 如何使用 bash for 循环和 sed 重复搜索和替换文件中的字符串?
- twitter-bootstrap - Bootstrap 侧柱 - 滑出模态
- docker - Pomelo / Docker / MySQL - 无法连接到任何指定的 MySQL 主机
- php - Laravel - 在模型中引入 trix 字段
- php - 如何使用 PHP curl 方法格式化 POST 请求?
- powerbi-embedded - 如何收听选择视觉对象的事件?
- python - 如何在 Python 中使用 ConfigParser() 读取列表中的列表?
- python - 如何处理flask-socketio中的事件?
- javascript - 以漂亮的 HTML 格式显示 JSON
- java - 使用内置排序功能对二维数组进行排序