篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby struct vs hash相关的知识,希望对你有一定的参考价值。
require 'benchmark'
require 'ostruct'
REP = 100000
User = Struct.new(:name, :age)
USER = "User".freeze
AGE = 21
Benchmark.bm 20 do |x|
x.report 'Struct' do
REP.times do |index|
u = User.new({:name => USER, :age => AGE})
u.name
u.age
end
end
x.report 'Hash' do
REP.times do |index|
t = {:name => USER, :age => AGE}
t[:name]
t[:age]
end
end
end