I’ve heard from some people that are worried about breaking apart large Rails views into smaller partials: How much time does rendering a partial really take? Will the performance impact of calling the partials outweigh the benefits in code readability?

I ran some numbers to give an example on how simple partial rendering compares to inline rendering, so we can discuss the tradeoff later. This is the code I used to benchmark, in a brand new Rails app (with config.cache_classes = true ):

app/views/test/show.html.erb <% require 'benchmark' Benchmark . bmbm do | x | x . report "inline" do 10000 . times do -%> <p> Hello! </p> <% end end x . report "partial" do 10000 . times do -%> <%= render partial: "hello" %> <% end end -%> <% end -%>

app/views/test/_hello.html.erb <p> Hello! </p>

And the results (using Ruby 2.1 and Rails 4.0.2, on a 2013 15” Retina Macbook Pro):

Rehearsal ------------------------------------------- inline 0.010000 0.000000 0.010000 ( 0.007045) partial 0.970000 0.090000 1.060000 ( 1.050433) ---------------------------------- total: 1.070000sec user system total real inline 0.010000 0.000000 0.010000 ( 0.005529) partial 0.920000 0.070000 0.990000 ( 0.997491)

So, a partial render runs at an average of about 0.1ms on a speedy machine. It’s much slower than rendering inline, but fast enough that it would be hard to notice when you also have things like URL generation, Rails helpers, and browser rendering time to think about.

Speed isn’t everything

If the performance of rendering partials was a lot worse, I’d still probably make the decision to break apart huge views.

There’s a phrase, Make It Work, Make It Right, Make It Fast. When you’re trying to fix a view that’s too big, you’re trying to get out of “Make it Work” mode, and you can’t just skip to “Make it Fast.” You’ll make your code less maintainable, and you could miss some opportunities for refactoring, which could lead to opportunities for caching, which could lead to even bigger performance benefits.

You won’t know until you measure

You don’t have to believe my numbers. I’d recommend that you didn’t! Ruby’s Benchmark library gives you some simple tools to run your own benchmarks. There are also tools for profiling your full stack, like New Relic and MiniProfiler. I use all three of these pretty regularly in my day-to-day work.

When you profile, always profile in production mode! The Rails development environment auto-reloads classes and views, which is useful while developing, but will kill your performance numbers.