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):
And the results (using Ruby 2.1 and Rails 4.0.2, on a 2013 15” Retina Macbook Pro):
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.