-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
perf: optimize code even further #40
Conversation
I measured this by first creating const luhn = require('./index.js') // or index-next
for (let i = 0; i < 1_000_000; i++) luhn('5512345678') And finally used hyperfine to measure: $ hyperfine 'node a.js' 'node b.js'
Benchmark 1: node a.js
Time (mean ± σ): 134.6 ms ± 1.3 ms [User: 131.1 ms, System: 4.3 ms]
Range (min … max): 133.5 ms … 139.6 ms 21 runs
Benchmark 2: node b.js
Time (mean ± σ): 50.9 ms ± 0.6 ms [User: 47.5 ms, System: 3.9 ms]
Range (min … max): 50.1 ms … 53.8 ms 55 runs
Summary
node b.js ran
2.65 ± 0.04 times faster than node a.js |
|
||
return sum % 10 === 0 | ||
let index = number.length | ||
let x2 = true |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changing bit
to a boolean led to a speed up, and then I thought that x2
was a better name, since it determines wether to multiply the number by 2 or not
|
||
while (index) { | ||
const value = number.charCodeAt(--index) - 48 | ||
if (value < 0 || value > 9) return false |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The previous implementation had sum
turn into NaN
which resulted in false
being returned in the end, so this should mimic that behaviour
let bit = 1 | ||
let sum = 0 | ||
let value | ||
const lookup = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Renamed this lookup
from array
since it's a lookup table for (x * 2) % 10
and array
felt very generic
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice!
This brings a speed up in all of the test cases I have tried:
5512345678
0000000000000000
4242424242424241
4242424242424242
551234- asd- asd- sa -d as9d0 sad9sd90sa 5678