Opensturt和Struct區別

c3tc3tc3t發表於2016-05-15

1 OpenStruct和Struct區別,Opestruct你需要建立時,直接給屬性賦值,而Struct需要先定義屬性後 ,再給屬性賦值。選擇哪個就看你對屬性賦值的時機,

2 Struct和Opensturt表示的屬性之間關係比hash更緊密一些。但是他們沒有作為類的例項方法,一組可選的函式,如果需要給屬性提供特殊方法,最好需要建立一個類

 

 

3 Openstruct可以使用hash轉換成一個物件
h = { a: 1, b: 2 }
o = OpenStruct.new(h)
o.a = 1
o.b = 2

4 Struct可以快速定義一個類

class MyClass < Struct.new(:a,:b,:c)
end

m = MyClass.new
m.a = 1

 

 5 Struct相比較penstruct,速度快, 但是openStruct可以動態新增屬性,


australia = OpenStruct.new(:country => "Australia", :population => 20_000_000)

australia.name='jack'

p australia

 


下面程式碼是測試Opensturct和Struct速度

require 'benchmark'
require 'ostruct'

REP = 100000

User = Struct.new(:name, :age)

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
end

相關文章