Last active
August 29, 2015 14:23
-
-
Save cedricpim/4bd588079a14d7b23f10 to your computer and use it in GitHub Desktop.
Struct vs Hash vs OpenStruct vs Class benchmark
This file contains 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 'benchmark' | |
require 'ostruct' | |
require 'memory_profiler' | |
i = 100000 | |
User = Struct.new(:name, :age) | |
USER = "User".freeze | |
AGE = 21 | |
HASH = { name: USER, age: AGE}.freeze | |
class Poro | |
attr_accessor :user, :age | |
def initialize(user, age) | |
@user = user | |
@age = age | |
end | |
end | |
Benchmark.bm 20 do |x| | |
x.report 'OpenStruct slow' do | |
i.times { |index| OpenStruct.new(name: "User", age: 21) } | |
end | |
x.report 'OpenStruct fast' do | |
i.times { |index| OpenStruct.new(HASH) } | |
end | |
x.report 'Struct slow' do | |
i.times { |index| User.new("User", 21) } | |
end | |
x.report 'Struct fast' do | |
i.times { |index| User.new(USER, AGE) } | |
end | |
x.report 'Hash slow' do | |
i.times { |index| Hash.new(user: "User", age: 21) } | |
end | |
x.report 'Hash fast' do | |
i.times { |index| Hash.new(HASH) } | |
end | |
x.report 'Class slow' do | |
i.times { |index| Poro.new("User", 21) } | |
end | |
x.report 'Class fast' do | |
i.times { |index| Poro.new(USER, AGE) } | |
end | |
end | |
j = 100 | |
results = {} | |
results[:openstruct_slow] = MemoryProfiler.report do | |
(1..j).map { |index| OpenStruct.new(name: "User", age: 21) } | |
end | |
results[:openstruct_fast] = MemoryProfiler.report do | |
(1..j).map { |index| OpenStruct.new(HASH) } | |
end | |
results[:struct_slow] = MemoryProfiler.report do | |
(1..j).map { |index| User.new("User", 21) } | |
end | |
results[:struct_fast] = MemoryProfiler.report do | |
(1..j).map { |index| User.new(USER, AGE) } | |
end | |
results[:hash_slow] = MemoryProfiler.report do | |
(1..j).map { |index| Hash.new(user: "User", age: 21) } | |
end | |
results[:hash_fast] = MemoryProfiler.report do | |
(1..j).map { |index| Hash.new(HASH) } | |
end | |
results[:klass_slow] = MemoryProfiler.report do | |
(1..j).map { |index| Poro.new("User", 21) } | |
end | |
results[:klass_fast] = MemoryProfiler.report do | |
(1..j).map { |index| Poro.new(USER, AGE) } | |
end | |
# Print a graph profile to text | |
results.each_pair do |type, result| | |
puts type | |
result.pretty_print | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment