How I Made Ruby Faster Than Ruby

https://news.ycombinator.com/rss Hits: 12
Summary

How I Made Ruby Faster than Ruby18·08·2025If you’re a Ruby programmer, you most probably will be familiar ERB templates and the distinctive syntax where you mix normal HTML with snippets of Ruby for embedding dynamic values in HTML. I wrote recently about P2, a new HTML templating library for Ruby, where HTML is expressed using plain Ruby. Now this is nothing new or even unique. There’s a lot of other Ruby gems that allow you to do that: Phlex, (my own) Papercraft and Ruby2html come to mind. What is different about P2 is that the template source code is always compiled into an efficient Ruby code that generates the HTML. In other words, the code you write inside a P2 template is actually never run, it just serves as a description of what you actually want to do. While there have been some previous attempts to use this technique for speeding up template generation, namely Phlex and Papercraft, to the best of my knowledge P2 is the first Ruby gem that actually employs this technique exclusively. In this post I’ll discuss how I took P2’s template generation performance from “OK” to “Great”. Along the way I was helped by Jean Boussier, a.k.a. byroot who not only showed me how far P2 still has to go in terms of performance, but also gave me some possible directions to explore. How P2 Templates Work Here’s a brief explanation of how P2 compiles template code. In P2, HTML templates are expressed as Ruby Procs, for example: ->(title:) { html { body { h1 title } } }.render(title: 'Hello from P2') # "<html><body><h1>Hello from P2</h1></body></html>" Calling the #render method will automatically compile and run the generated code, which will look something like the following: ->(__buffer__, title:) { __buffer__ << "<html><body><h1>" __buffer__ << ERB::Escape.html_escape((title).to_s) __buffer__ << "</h1></body></html>" __buffer__ } As you can see, while the original source code is made of nested blocks, the generated code takes an additional __buffer__ parameter and pushes sni...

First seen: 2025-08-20 05:05

Last seen: 2025-08-20 16:20