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

Ticket #1423: compare-benchmark.rb

File compare-benchmark.rb, 0.6 kB (added by Ulysses, 3 years ago)

Benchmark of MD5 vs String#hash vs. String==

Line 
1 require 'md5'
2 require 'benchmark'
3
4 Benchmark.bm do |b|
5   n = 10000
6   objects = [{:a => 20, :b => 30}, ["Hello, Sexy", "How are you?"] * 100, "THis is a bunch of text\n" * 100]
7   dumps = objects.collect {|o| Marshal.dump o}
8
9   md5s = dumps.collect {|d| MD5.digest d}
10   b.report("MD5") do
11     n.times { dumps.each_with_index {|d, i| MD5.digest(d) == md5s[i] } }
12   end
13
14   hashes = dumps.collect {|d| d.hash}
15   b.report("String#hash") do
16     n.times { dumps.each_with_index {|d, i| d.hash == hashes[i] && d == dumps[i]} }
17   end
18
19   b.report("String#==") do
20     n.times { dumps.each_with_index {|d, i| d == dumps[i]} }
21   end
22
23  
24  
25 end