How I Made Ruby Faster Than Ruby
6 days ago
- #Performance
- #Ruby
- #Templating
- P2 is a new HTML templating library for Ruby that compiles template source code into efficient Ruby code for generating HTML.
- P2 templates are expressed as Ruby Procs, which are compiled into code that pushes HTML snippets into a buffer, with dynamic values properly escaped.
- The compilation process involves parsing the template's source code into a Prism AST, translating relevant nodes into custom types, and then generating optimized Ruby code.
- Performance improvements in P2 were achieved by separating static and dynamic HTML generation, removing rescue clauses, using frozen string literals, and switching to ERB::Escape.html_escape.
- Benchmark results show P2's compiled templates are now on par with ERB and ERubi, significantly faster than non-compiled alternatives like Papercraft and Phlex.
- The article highlights that Ruby can be very fast when code is optimized properly, and suggests the Ruby-to-Ruby compilation technique could be useful for other DSLs.