Is Ruby 2.3 Faster? Rails ERB Template Rendering Performance
Ruby 2.3 was released last month with yet another bunch of performance improvements. But is it really faster than 2.2? Let's take a look.
This is the third post in my series about Ruby 2.3 performance. This time we'll look at the html escaping performance improvements that, in theory, can yield dramatic speedup in Rails template rendering.
At the very end of the Ruby 2.3.0 release news one can find these two lines:
* CGI.escapeHTML is optimized with C extention. https://github.com/ruby/ruby/pull/1164
As a Rails developer, I immediately recognized the importance of this. Rails >= 3.0 by default escapes all strings rendered with
<%= %>. The function that does it is
ERB::Util#html_escape, and that internally calls
CGI.escapeHTML. So the change means that Rails template rendering should become a lot faster in Ruby 2.3.
Let's see if this is the case. Let's write a simple example that would render 100k strings that should be HTML escaped:
This program does the same thing any Rails app would do, except that in Rails you don't need to explicitly call html_escape.
I ran this program with both Ruby 2.2.3 and 2.3.0, and also measured the memory consumption. Here's what I got:
|0.386 ± 0.008 s||110 MB||0.099 ± 0.003 s||34 MB|
Yay! Ruby 2.3 is almost 4x faster in this example. And it uses less memory too (and therefore is not likely to cause the extra GC).
Is it really the HTML escaping that got faster? One could prove it by profiling, but you can also compare the performance without the
html_escape call in the template. These are my results:
|0.067 ± 0.003 s||14 MB||0.053 ± 0.001 s||14 MB|
Ruby 2.3 is only slighly faster than 2.2 here. And that proves that in the previous example it was the new HTML escaping code that made the difference.
Why was it so fast? Simple! It's now written in C!
So, I got the 4x speedup in my template rendering example. Will you see it in your app? Well, that depends. Your template might be much smaller than mine. Or your strings might not need HTML escaping. Both factors cancel out the effect of the optimization. As usual, you should upgrade and measure yourself.
I can't really report any performance measurements from my own projects because I've been happily using Slim in my templates for the last 3 years. And that already uses custom HTML escaping code, also written in C.
Please let me know if Ruby 2.3 significantly improved the template rendering performance in your Rails app.
ERB template rendering got significantly faster with Ruby 2.3. Rewriting Ruby code in C definitely makes things faster :)
|Next:||Is Ruby 2.3 Faster? Immutable (Frozen) String Literals Performance|
|Previous:||Is Ruby 2.3 Faster? Date Parsing Performance|