Skip to content

Improve Base64.urlsafe_encode64 performance - #5

Merged
nobu merged 2 commits into
ruby:masterfrom
jcmfernandes:improve-urlsafe_encode64-performance-removing-padding
Sep 5, 2021
Merged

Improve Base64.urlsafe_encode64 performance#5
nobu merged 2 commits into
ruby:masterfrom
jcmfernandes:improve-urlsafe_encode64-performance-removing-padding

Conversation

@jcmfernandes

Copy link
Copy Markdown
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
Copy Markdown
ContributorAuthor

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

nobu commented Sep 2, 2021

Copy link
Copy Markdown
Member

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

@jcmfernandes

jcmfernandes commented Sep 2, 2021

Copy link
Copy Markdown
ContributorAuthor

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.

@nobu
nobu merged commit 1f08f53 into ruby:masterSep 5, 2021
Sign up for freeto 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

@jcmfernandes@nobu