Skip to content
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

Improve performance by using bytesize when comparing if the string changed #690

Merged
merged 2 commits into from Mar 22, 2024

Conversation

davekaro
Copy link
Contributor

length slows down as the string grows (appears to be O(n)). bytesize stays the same O(1). Even on very small strings like "<h1>", bytesize is much faster than length. By swapping over to bytesize we can see an overall improvement in Phlex bench.rb:

Before (using length):

ruby 3.3.0 (2023-12-25 revision 5124f9ac75) +YJIT [arm64-darwin23]
Warming up --------------------------------------
                Page    13.160k i/100ms
Calculating -------------------------------------
                Page    133.259k (± 0.9%) i/s -    671.160k in   5.036897s

After (using bytesize):

ruby 3.3.0 (2023-12-25 revision 5124f9ac75) +YJIT [arm64-darwin23]
Warming up --------------------------------------
                Page    15.000k i/100ms
Calculating -------------------------------------
                Page    154.814k (± 1.2%) i/s -    780.000k in   5.039022s

If we further tune bench.rb as I've done in this PR to more accurately represent what might be a typical "string length" when using Phlex (think larger components or full page views), we see an even more dramatic improvement:

Before (using length on larger string):

ruby 3.3.0 (2023-12-25 revision 5124f9ac75) +YJIT [arm64-darwin23]
Warming up --------------------------------------
                Page    73.000 i/100ms
Calculating -------------------------------------
                Page    734.131 (± 0.4%) i/s -      3.723k in   5.071408s

After (using bytesize on larger string):

ruby 3.3.0 (2023-12-25 revision 5124f9ac75) +YJIT [arm64-darwin23]
Warming up --------------------------------------
                Page   520.000 i/100ms
Calculating -------------------------------------
                Page      5.243k (± 0.6%) i/s -     26.520k in   5.058093s

Comes to about a 7x speed increase. Always faster, with potential for huge gains. I had a page go from 15 seconds to 300ms with this change (50x speedup). This was a rare page of over 3 megabytes of HTML all generated by Phlex, but still pretty fun.

@joeldrapper joeldrapper merged commit db07a93 into phlex-ruby:main Mar 22, 2024
21 checks passed
@davekaro davekaro deleted the string-performance branch March 22, 2024 17:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

None yet

2 participants