Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #8976: perform_exist.rb

File perform_exist.rb, 2.1 kB (added by lifofifo, 1 year ago)

Benchmarking for various implementations

Line 
1 require 'benchmark'
2
3 def do_benchmark
4   n = 10000
5   Benchmark.bm do |x|
6     # Existing item by id
7     x.report { n.times do Item.exists?(1); end }
8    
9     # fake fake id. Gimme false
10     x.report { n.times do Item.exists?(1384); end }
11    
12     # Existing item by conditions
13     x.report { n.times do Item.exists?(:name => "sunshine"); end }
14    
15     # Existing item by conditions matching multiple records
16     x.report { n.times do Item.exists?((['name LIKE ?', "%shine%"])); end }
17
18     # fake fake name. Gimme false
19     x.report { n.times do Item.exists?(:name => "moonlight"); end }
20   end
21 end
22
23 puts "Existing AR implementation"
24 do_benchmark
25
26 class ActiveRecord::Base
27   def self.exists?(id_or_conditions)
28     !find(:first, :select => "#{table_name}.#{primary_key}", :conditions => expand_id_conditions(id_or_conditions)).nil?   
29   rescue ActiveRecord::ActiveRecordError
30     false
31   end
32 end
33
34 puts "Josh's Implementation"
35 do_benchmark
36
37 class ActiveRecord::Base
38   def self.exists?(id_or_conditions)
39     !find(:all, :select => "#{table_name}.#{primary_key}", :conditions => expand_id_conditions(id_or_conditions), :limit => 1).empty?
40   end
41 end
42
43 puts "Lifo's Implementation"
44 do_benchmark
45
46 # $ script/runner lib/perform_exist.rb
47 # Existing AR implementation
48 #       user     system      total        real
49 #   7.130000   0.320000   7.450000 (  8.952531)
50 #   6.470000   0.300000   6.770000 (  8.341876)
51 #   6.960000   0.290000   7.250000 (  8.596609)
52 #   6.710000   0.300000   7.010000 (  8.178951)
53 #   6.470000   0.290000   6.760000 (  7.986819)
54 # Josh's Implementation
55 #       user     system      total        real
56 #   4.780000   0.290000   5.070000 (  6.780793)
57 #   4.410000   0.280000   4.690000 (  5.622038)
58 #   4.800000   0.290000   5.090000 (  6.184860)
59 #   4.500000   0.290000   4.790000 (  5.957613)
60 #   4.420000   0.260000   4.680000 (  5.640687)
61 # Lifo's Implementation
62 #       user     system      total        real
63 #   4.730000   0.280000   5.010000 (  6.459801)
64 #   4.330000   0.280000   4.610000 (  5.523227)
65 #   4.680000   0.280000   4.960000 (  5.908463)
66 #   4.290000   0.270000   4.560000 (  5.482114)
67 #   4.380000   0.270000   4.650000 (  5.612552)