Instantly share code, notes, and snippets.

@pdlug /results Secret
Last active Aug 29, 2015

Embed
What would you like to do?
Performance comparison of several roughly equivalent representations of # data objects. Compares Struct, OpenStruct, Hashie (Dash and Mash), and # ActiveModel.
user system total real
OpenStruct slow 1.710000 0.020000 1.730000 ( 1.794663)
OpenStruct fast 1.660000 0.020000 1.680000 ( 1.724525)
Struct slow 0.050000 0.000000 0.050000 ( 0.045123)
Struct fast 0.030000 0.000000 0.030000 ( 0.035193)
Hashie Dash 0.370000 0.000000 0.370000 ( 0.370817)
Hashie Mash 0.410000 0.000000 0.410000 ( 0.435168)
ActiveModel 0.220000 0.000000 0.220000 ( 0.228006)
#!/usr/bin/env ruby
# encoding: utf-8
# Performance comparison of several roughly equivalent representations of
# data objects. Compares Struct, OpenStruct, Hashie (Dash and Mash), and
# ActiveModel.
#
# Based on:
# http://stackoverflow.com/a/4459132
require 'benchmark'
require 'ostruct'
require 'hashie'
require 'active_model'
REP = 100000
User = Struct.new(:name, :age)
class UserDash < Hashie::Dash
property :name
property :age
end
class UserAM
include ActiveModel::Model
attr_accessor :name, :age
end
USER = "User".freeze
AGE = 21
HASH = {:name => USER, :age => AGE}.freeze
Benchmark.bm 20 do |x|
x.report 'OpenStruct slow' do
REP.times do |index|
OpenStruct.new(:name => "User", :age => 21)
end
end
x.report 'OpenStruct fast' do
REP.times do |index|
OpenStruct.new(HASH)
end
end
x.report 'Struct slow' do
REP.times do |index|
User.new("User", 21)
end
end
x.report 'Struct fast' do
REP.times do |index|
User.new(USER, AGE)
end
end
x.report 'Hashie Dash' do
REP.times do |index|
UserDash.new(HASH)
end
end
x.report 'Hashie Mash' do
REP.times do |index|
Hashie::Mash.new(HASH)
end
end
x.report 'ActiveModel' do
REP.times do |index|
UserAM.new(HASH)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment