AR dynamic finders are soooo slow..NOT 3

Posted by pratik
on Saturday, August 18

Really ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
require 'benchmark'

Benchmark.bm do |x|
  n = 10000
  x.report do
    n.times do
      # "shit" exists
      Item.find_all_by_name "shit"
      Item.find_by_name "shit"      
      
      # "fud" does not exist
      Item.find_all_by_name "fud"
      Item.find_by_name "fud"
    end 
  end
  
  x.report do 
    n.times do  
      Item.find :all, :conditions => ["name = ?", "shit"]
      Item.find :first, :conditions => ["name = ?", "shit"]
      
      Item.find :all, :conditions => ["name = ?", "fud"]
      Item.find :first, :conditions => ["name = ?", "fud"]
    end 
  end
end

# $ script/runner benchmark.rb 
#       user     system      total        real
#  28.510000   1.270000  29.780000 ( 36.924108)
#  26.100000   1.230000  27.330000 ( 34.318721)

So think again before you blame AR dynamic finders. Difference of 2 seconds for 40,000 queries shouldn’t really make anything slower.

Comments

Leave a response

  1. Amit SolankiSeptember 24, 2007 @ 01:32 PM

    Someone has advised me to minimize use of dynamic finders as they are too slow. I never had any strong evidence against it since I never had such a big database to work on and prove it. Atleast now I have a concrete answer.

    Thanks for the post.

  2. PratikSeptember 24, 2007 @ 03:23 PM

    Also, as of [7510] rails will define a method dynamically whenever you use dynamic finder.

  3. swombatJanuary 06, 2008 @ 12:01 PM

    Great to see more evidence against premature optimisation. Even if dynamic finders were half the speed of raw SQL (which may well be the case of other Rails features), I’d argue very strongly against dropping finders unless you have a live or almost-live application with a clearly identified bottleneck where you know that making this switch is the best way to improve performance.

    (see my article on premature optimisation: http://www.inter-sections.net/2007/11/08/premature-optimisation/ )

    Daniel

Comment