microlinkhq / async-ratelimiter

Rate limit made simple, easy, async.
MIT License
318 stars 23 forks source link

perf: use number constructor #48

Closed Kikobeats closed 5 months ago

Kikobeats commented 5 months ago

saving ~500ms cpu time processing 15M calls

const toNumber = str => {
  let result = 0
  for (let i = 0; i < str.length; i++) {
    result = result * 10 + (str.charCodeAt(i) - 48) // 48 is the ASCII code for '0'
  }
  return result
}

function benchmark (name, cb) {
  const t0 = performance.now()
  for (let i = 0; i < 15e7; i++) {
    cb()
  }
  const t1 = performance.now()
  console.log(`${name} took ${t1 - t0} ms`)
}

const process1 = () => Number('9.9') // 9.9
const process2 = () => parseInt('9.9', 10) // 9
const process3 = () => Number('12') // 12
const process4 = () => parseFloat('12') // 12
const process5 = () => toNumber('12') // 12

benchmark('process1', process1) // 85.34212500000001 ms
benchmark('process2', process2) // 645.28675 ms
benchmark('process3', process3) // 637.7701669999999 ms
benchmark('process4', process4) // 807.0241250000001 ms
benchmark('process5', process5) // 797.092791 ms