-
Notifications
You must be signed in to change notification settings - Fork 15
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
Use canonical maps/arrays instead of new Function #22
Conversation
code += '}\n' | ||
function optionNumberToString (number) { | ||
const string = OPTIONS_BY_NUMBER[number] | ||
if (string) return string |
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.
If 0
is intended to be supported [somehow], you could use string !== undefined
.
Little to no difference to the benchmark.
optionNumberToStringNew: 1.537s
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.
Thank you for your contribution, @dcousens! :) This is a great improvement over the old version. As to this particular check: As 0
is a reserved number, I think it is safe to keep it as is :)
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.
Sorry, this comment should have been on optionStringToNumber
, but the implications of the comment remain the same. (number !== undefined
)
Little to no difference to the benchmark.
optionStringToNumberNew: 2.250s
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.
LGTM :) @mcollina: Could you release a new version with these changes?
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.
lgtm
Resolves #3
Instead of using
new Function
, this pull request replace the two functions with an array lookup (generated at runtime) and a typical object lookup (static).I additionally noticed that the previous
optionStringToNumber
actually returned a string if the string was found (e.g'11'
instead of11
), otherwise it returned a number from theparseInt
.I assumed that was a bug, but happy to switch the values in
OPTIONS_BY_NUMBER
if not.node -v
Results
Method
Benched with the following code.
You could use
benchmark
as an improvement.The benchmark runs are shown sequentially, but if you want to check for less hot-path results, you can omit them or change the order.
The results appear to be consistent.
Disclaimer: I don't actually think this function needs to be fast, but,
new Function
was a red flag to me.