Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling a partial an expensive operation?

Can I use partials as much as I want or do I have to restrain myself to avoid bringing my views to a crawl under much traffic?

like image 598
Daniel Rikowski Avatar asked Dec 05 '09 16:12

Daniel Rikowski


1 Answers

There's an obvious overhead using partial but this isn't something you should probably worry about.

Partials are files. When you render an action without partials, your action "costs" 1 file (that's not totally true, but this is to simplify the explanation). If your action renders 4 partials, you end up with a cost of 5. This means, you have 4 additional IO calls and the real cost for each call depends on your server load, server performances and so on.

But does this cost matter? In my experience, for the 99% of times no. Also noteworthy, the benefits of using partials in terms of code readability and maintainability usually are worth the choice.

If performances must be a key feature, you should probably look for speed and improvements elsewhere.

Remember: Ruby is not a super-fast programming language and code expressiveness always took the first place in favor of performances. Rails implicitly agree to this convention, albeit the Rails team has always focused on performances (and Rails 3 it's the practical demonstration there's always place for improvements)

That said, you can safely use partials and reduce the application overhead with some clever caching mechanism. For example, you can place collection rendering within a cache block so that a render collection statement will be executed only once then your app will simply load 1 cache file instead of 10 un-cached partials.

One of the most sneak errors I made many times at the beginning was to worry about performances in the wrong way, that said, without actually running benchmarks. I remember once when I was trying to drop one single database query in favor of an hard coded hash because "the query costs", without realizing there was an other stupid query that was loading an entire table collection without the include statement, that resulted in running the second query 3 times slower.

So, if you really care about performance, you probably shouldn't avoid using partials but instead make sure you are taking advantage of all the other features Rails provides you to scale your application.

like image 74
Simone Carletti Avatar answered Oct 06 '22 11:10

Simone Carletti