-
-
Notifications
You must be signed in to change notification settings - Fork 27
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
Implementing linear time suffix trimming #7
Implementing linear time suffix trimming #7
Conversation
index.js
Outdated
if (a.length > b.length) { | ||
a = b; | ||
b = swap; | ||
} |
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.
Can you add a short code comment on why you're swapping here?
index.js
Outdated
@@ -19,6 +26,15 @@ module.exports = function (a, b) { | |||
return aLen; | |||
} | |||
|
|||
while (aLen > 0 && (a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen))) { |
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.
Can you add a comment about what this does (suffix trimming)?
I've added some comments. Note also that swapping |
This is amazing. Thank you @Yomguithereal :) |
I'll come back when I fix my prefix trimming (if this is still useful performance-wise) & if I find evidence that caching the longest or shortest or both char codes can be useful or not. |
Pretty good improvement actually: cf30e86 🎉 |
Hello again @sindresorhus. This PR adds linear time suffix trimming to your function. This should give you an edge (at least it did on the benchmark I ran), but I advise you run your own just to be sure (maybe with more use cases and swapping the strings already present).
The idea is to trim the suffix of both strings linearly until they start to differ.
The strange
~-
operation used here is the bitwise way to perform a-1
operation on a number. It speeds up the computation a bit on my benchmarks.I can also implement prefix trimming but while writing this PR, I noticed that I did something wrong and my prefix trimming is actually erroneous so I need to fix it. However, since it means performing some more arithmetical operations, I fear it could slow down things rather than improving the performance of the function. I will come back later when my function is fixed to tell you if it's worth it to add prefix trimming then.
Have a nice day.