标签:
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
下面代码是测试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
标签:
原文地址:http://www.cnblogs.com/or2-/p/5495421.html