Matthew Lindfield Seager

Matthew Lindfield Seager

The more I learn about programming, the more I discover how “inefficient” it can be…

While debugging my Rails apps I’ve noticed a single line of my code might cause dozens or even hundreds of other lines of Ruby code in various Rails gems to be executed.

Lately I’ve been learning that each of those hundreds of lines of Ruby has to be tokenised, then the tokens parsed into AST nodes and then the AST nodes compiled into YARV instructions. Each line of Ruby requires in 5-10 YARV instructions.

YARV is written mostly in C so each YARV instruction usually results in multiple lines of C code being run.

Each line of C then needs to be converted to assembly code for the current processor architecture.

The assembly code then gets converted to machine code, the actual instructions the CPU executes.

All that from a single line in my Rails app!

N.B. The deeper down the stack we go, the less confident I am of the details. I’m happy to be corrected if you notice I’ve got anything majorly wrong but don’t let technical details distract you from the main point :)


There are so many layers of “inefficiency” from the code’s perspective!!! And yet, even with all that conversion and compilation and manipulation, the result is usually displayed pretty much instantly the moment I press enter in the Rails console or hit “go” in my browser.

Each of those layers is like a carefully machined gear, multiplying the power of the layers above. The result is that we can write clear and readable Ruby code, mostly oblivious to the mountain of code we’re relying on to do the actual work of updating a database, responding to an HTTP request or performing a complex calculation.

To me the key takeaway (other than being grateful for all that hard work) is that I shouldn’t worry about the “efficiency” of my Ruby code, especially not to begin with. The computer can deal with an extra line of code, one more variable or an additional method call. Instead I should focus entirely on making my code easy to read, easy to reason about and easy to refactor. I need to improve the efficiency of my coding as a whole, not my code.