Optimize Messagebus::Message.decode method#383
Open
moberegger wants to merge 3 commits intodiscourse:mainfrom
Open
Optimize Messagebus::Message.decode method#383moberegger wants to merge 3 commits intodiscourse:mainfrom
Messagebus::Message.decode method#383moberegger wants to merge 3 commits intodiscourse:mainfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Saw this coming up as a hotspot in our production profiles.
Found a few optimization candidates that looked lower risk to implement:
encoded.to_iinstead ofencoded[0, s1 + 1].to_i.String#to_iwill stop parsing at the first non-numeric character, so calling it on the full string yields the same result as extracting a substring first. This eliminates a string allocation.byteindexinstead ofindex. Since the pipe delimiter|is a single-byte ASCII character, this produces the same result but skips character-encoding boundary checks (At least that is my undertanding). (Note: I believe Ruby 3.2+ is required forbyteindex, but this is specified is the minimum Ruby version in the gemspec.)bytesliceinstead of[]. If the encoded format is always ASCII-safe,byteslicecan skip the character-encoding boundary checks thatString#[]performs. This is a cheaper operation for the same result.encoded.bytesizeinstead ofencoded.size. This avoids a character-length scan on the string.include?guard beforegsub!. Saves on agsub!in situations where there is nothing to substitute. I am not sure how common the$$123$$escape sequence will be present, but this will skip that overhead when it's not necessary.Benchmarks against
Messagebus::Message.decode