switch/case
быстрее. Он работает примерно в 2,5 раза быстрее.
Я запустил некоторый код, используя moment
для определения времени.
Распечатки были реализованы, чтобы убедиться, что они работают правильно, но на этапе синхронизации я закомментировал их.
Я проверил наличие элементов в первом массиве, во втором и вообще без массива.
Каждая версия работала 10 000 000 и результаты в миллисекундах.
Это работало на MacBook Pro, 2,2 ГГц процессоре Intel Core i7, 16 ГБ оперативной памяти.
Код:
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