Ruby 学习:Struct

Struct 与 Hash,Class 的不同使用场景
更新于: 2021-12-30 06:47:51

 Struct 与 Class

可以做与 class 类似的事情,但可以用来处理少量使用,或者匿名 Class 的场景。

class Person
  attr_accessor :name, :email
end

SPerson = Struct.new(:name, :email) do
  def to_s
    "#{name} <#{email}>"
  end
end

p1 = Person.new
p1.name = "John Doe"

p2 = SPerson.new("Mary", "m@example.com")

puts p1.name
puts p2.name

Struct 与 Hash

Hash 只能用来放数据 ,但 stuct 还可以用来添加方法

性能方面

结论:hash最快、class稍慢一点,struct比class又更慢一点,openstruct最慢(非常非常慢,因此不要用它)

require 'ostruct'    # 提供openstruct
require 'benchmark'

COUNT = 10_000_000
NAME = "Test Name"
EMAIL = "test@example.org"

class Person
  attr_accessor :name, :email
end

Benchmark.bm(13) do |x|
  x.report("hash:") do
    COUNT.times do
      p = {name: NAME, email: EMAIL}
    end
  end

  x.report("struct:") do
    PersonStruct = Struct.new(:name, :email)
    COUNT.times do
      p = PersonStruct.new
      p.name = NAME
      p.email = EMAIL
    end
  end

  x.report("class:") do
    COUNT.times do
      p = Person.new
      p.name = NAME
      p.email = EMAIL
    end
  end
  
  x.report("openstruct:") do
    COUNT.times do
     p = OpenStruct.new
     p.name = NAME
     p.email = EMAIL
   end
  end
  
end
                    user     system      total        real
hash:           0.836551   0.000639   0.837190 (  0.837230)
struct:         1.713467   0.000065   1.713532 (  1.713540)
class:          1.130315   0.000000   1.130315 (  1.130318)
openstruct:    51.333243   0.000012  51.333255 ( 51.333304)

参考