| 1 |
require 'benchmark' |
|---|
| 2 |
|
|---|
| 3 |
def do_benchmark |
|---|
| 4 |
n = 10000 |
|---|
| 5 |
Benchmark.bm do |x| |
|---|
| 6 |
|
|---|
| 7 |
x.report { n.times do Item.exists?(1); end } |
|---|
| 8 |
|
|---|
| 9 |
|
|---|
| 10 |
x.report { n.times do Item.exists?(1384); end } |
|---|
| 11 |
|
|---|
| 12 |
|
|---|
| 13 |
x.report { n.times do Item.exists?(:name => "sunshine"); end } |
|---|
| 14 |
|
|---|
| 15 |
|
|---|
| 16 |
x.report { n.times do Item.exists?((['name LIKE ?', "%shine%"])); end } |
|---|
| 17 |
|
|---|
| 18 |
|
|---|
| 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 |
|
|---|
| 47 |
|
|---|
| 48 |
|
|---|
| 49 |
|
|---|
| 50 |
|
|---|
| 51 |
|
|---|
| 52 |
|
|---|
| 53 |
|
|---|
| 54 |
|
|---|
| 55 |
|
|---|
| 56 |
|
|---|
| 57 |
|
|---|
| 58 |
|
|---|
| 59 |
|
|---|
| 60 |
|
|---|
| 61 |
|
|---|
| 62 |
|
|---|
| 63 |
|
|---|
| 64 |
|
|---|
| 65 |
|
|---|
| 66 |
|
|---|
| 67 |
|
|---|