console.clear()
let a = []
// populating array data
for (let i = 0; i < 10000; i++) {
    a.push(i)
}
let testNum = 9000
let found
let totalMS4ForLoop = 0
let totalMS4ForIn = 0
let totalMS4ForOf = 0
let totalMS4IndexOf = 0
let start
let end
// simulating 10000 requests which are come consecutively
for (o = 0; o < 10000; o++) {
start = Date.now()
  for (let i = 0; i < a.length; i++) {
    if (a[i] == testNum) { found = a[i]; break }
  }
  end = Date.now()
  totalMS4ForLoop += end - start
start = Date.now()
  for (let j in a) {
    if (a[j] == testNum) { found = a[j]; break }
  }
  end = Date.now()
  totalMS4ForIn += end - start
start = Date.now()
  for (let item of a) {
    if (item == testNum) { found = item; break }
  }
  end = Date.now()
  totalMS4ForOf += end - start
start = Date.now()
  found = a[a.indexOf(testNum)]
  end = Date.now()
  totalMS4IndexOf += end - start
}
console.log("10000x10000 for-loop executions took total " + totalMS4ForLoop + " ms.")
console.log("10000x10000 for-in executions took total " + totalMS4ForIn + " ms.")
console.log("10000x10000 for-of executions took total " + totalMS4ForOf + " ms.")
console.log("10000x10000 indexOf executions took total " + totalMS4IndexOf + " ms.")

10000x10000 for-loop executions took total 60 ms.
10000x10000 for-in executions took total 1265 ms.
10000x10000 for-of executions took total 77 ms.
10000x10000 indexOf executions took total 14 ms.

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注