Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Speed test for two digg implementations
module Digg
class Digger
attr_reader :path
def initialize(*path)
@path = path
end
def call(matter)
path.inject(matter) do |memo, key|
(memo.respond_to?(:[]) && memo[key]) || break
end
end
end
module Core
def digg(*path)
path.inject(self) do |memo, key|
(memo.respond_to?(:[]) && memo[key]) || break
end
end
end
end
Array.send :include, Digg::Core
Hash.send :include, Digg::Core
require 'open-uri'
require 'json'
people_json = []
open('http://api.randomuser.me/?results=100') do |f|
people_json << JSON.parse( f.read )
end
require 'benchmark/ips'
path = [0, 'results', 5, 'user', 'name', 'first']
digger = Digg::Digger.new(0, 'results', 5, 'user', 'name', 'first')
Benchmark.ips do |x|
x.report("people_json.digg(...)") do
people_json.digg(0, 'results', 5, 'user', 'name', 'first')
end
x.report("people_json.digg(*)") do
people_json.digg(*path)
end
x.report("digger.call(...)") do
digger.call(people_json)
end
x.compare!
end
Calculating -------------------------------------
people_json.digg 23.540k i/100ms
people_json.digg(*) 22.190k i/100ms
digger.call(...) 19.954k i/100ms
-------------------------------------------------
people_json.digg 269.242k (±18.4%) i/s - 1.295M
people_json.digg(*) 301.677k (±14.2%) i/s - 1.465M
digger.call(...) 341.138k (±12.6%) i/s - 1.696M
Comparison:
digger.call(...): 341137.8 i/s
people_json.digg(*): 301677.0 i/s - 1.13x slower
people_json.digg: 269241.8 i/s - 1.27x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment