Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

jcmfernandes
Copy link
Contributor

Creating this here as asked in ruby/ruby#4802

Improves the method's performance when asked to remove padding.

str.delete!("=") iterates over the entire string looking for the equals
character, but we know that we will, at most, find two at the end of the
string.

Improves the method's performance when asked to remove padding.

str.delete!("=") iterates over the entire string looking for the equals
character, but we know that we will, at most, find two at the end of the
string.
@jcmfernandes
Copy link
Contributor Author

Some benchmarks:

Input generated with SecureRandom.alphanumeric.
.urlsafe_encode64 being called with padding: false.

4 kB input

Warming up --------------------------------------
NEW #urlsafe_encode64
                        14.230k i/100ms
OLD #urlsafe_encode64
                         7.588k i/100ms
Calculating -------------------------------------
NEW #urlsafe_encode64
                        141.104k (± 2.5%) i/s -      1.423M in  10.091936s
OLD #urlsafe_encode64
                         88.993k (± 5.5%) i/s -    887.796k in  10.009833s

Comparison:
NEW #urlsafe_encode64:   141104.0 i/s
OLD #urlsafe_encode64:    88993.5 i/s - 1.59x  (± 0.00) slower
4 MB input

Warming up --------------------------------------
NEW #urlsafe_encode64
                        13.000  i/100ms
OLD #urlsafe_encode64
                         8.000  i/100ms
Calculating -------------------------------------
NEW #urlsafe_encode64
                        136.878  (± 2.9%) i/s -      1.378k in  10.074976s
OLD #urlsafe_encode64
                         87.759  (± 2.3%) i/s -    880.000  in  10.030723s

Comparison:
NEW #urlsafe_encode64:      136.9 i/s
OLD #urlsafe_encode64:       87.8 i/s - 1.56x  (± 0.00) slower

@nobu
Copy link
Member

nobu commented Sep 2, 2021

str.chomp!("=") and str.chomp!("=") or str.chomp!("==") or str.chomp!("=") will work too.

@jcmfernandes
Copy link
Contributor Author

jcmfernandes commented Sep 2, 2021

str.chomp!("=") and str.chomp!("=") or str.chomp!("==") or str.chomp!("=") will work too.

Beautiful! 😍

EDIT:
I reran the benchmark and the performance is similar so I'm going with @nobu's idiomatic code.

Thanks @nobu!
@nobu nobu merged commit 1f08f53 into ruby:master Sep 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants