Forked from conorgriffin/array_process_benchmark.rb
Last active
August 29, 2015 14:07
-
-
Save jrunning/2bf920bd438336c2be48 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'set' | |
require 'benchmark/ips' | |
def process_old(list) | |
list.join(" ").split.uniq | |
end | |
def process_set(list) | |
unique = Set.new | |
list.each {|str| unique.merge(str.split) } | |
unique | |
end | |
def process_hash(list) | |
unique = {} | |
list.each do |str| | |
str.split.each {|word| unique[word] = true unless unique.key?(word) } | |
end | |
unique.keys | |
end | |
words = %w[ alpha bravo charlie delta echo foxtrot golf hotel india juliet | |
kilo lima mike november oscar papa quebec romeo sierra tango uniform | |
victor whiskey xray yankee zulu ] | |
# Returns a string of between 2 and 12 words chosen randomly from the | |
# given array | |
def rand_words_str(words) | |
words.sample(rand 2..12).join(" ") | |
end | |
list = Array.new(1000) { rand_words_str(words) } | |
Benchmark.ips do |x| | |
x.report("Old") do | |
res1 = process_old(list) | |
end | |
x.report("Set") do | |
res2 = process_set(list) | |
end | |
x.report("Hash") do | |
res3 = process_hash(list) | |
end | |
x.compare! | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Calculating ------------------------------------- | |
Old 98 i/100ms | |
Set 34 i/100ms | |
Hash 58 i/100ms | |
------------------------------------------------- | |
Old 995.9 (±1.4%) i/s - 4998 in 5.019369s | |
Set 343.5 (±1.7%) i/s - 1734 in 5.049819s | |
Hash 587.1 (±1.7%) i/s - 2958 in 5.039485s | |
Comparison: | |
Old: 995.9 i/s | |
Hash: 587.1 i/s - 1.70x slower | |
Set: 343.5 i/s - 2.90x slower |
So I cloned your repo and removed the |times|
from the first method above and re-ran the test using your code. Here's the results as per my comment on SO.
Calculating -------------------------------------
New 152 i/100ms
Old 388 i/100ms
-------------------------------------------------
New 1529.7 (±1.2%) i/s - 7752 in 5.068305s
Old 3910.0 (±1.2%) i/s - 19788 in 5.061618s
Comparison:
Old: 3910.0 i/s
New: 1529.7 i/s - 2.56x slower
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Aren't you missing
|times|
for the 'old' method?