Ruby Class vs Struct

后端 未结 5 823
滥情空心
滥情空心 2021-02-02 08:48

I have seen codebases using Structs to wrap around attributes and behavior inside a class. What is the difference between a Ruby Class and a Struct? And when should one be used

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-02 09:39

    There is quite a big practical performance difference, example behavior in ruby 2.6.3p62:

                              user       system     total     real
    Struct create and access  3.052825   0.005204   3.058029  (3.066316)
    Class create and access   0.738605   0.001467   0.740072  (0.743738)
    

    Example code:

    require 'benchmark'
    
    REP=1000000
    SUser = Struct.new(:name, :age)
    DATA = { name: "Harry", age: 75 }
    
    class User
      attr_accessor :name, :age
      def initialize(name:, age:)
        @name = name
        @age = age
      end
    end
    
    Benchmark.bm 20 do |x|
      x.report 'Struct create and access' do
        REP.times do
          user = SUser.new(DATA)
          "#{user.name} - #{user.age}"
        end
      end
      x.report 'Class create and access' do
        REP.times do
          user = User.new(DATA)
          "#{user.name} - #{user.age}"
        end
      end
    end
    

提交回复
热议问题