When is it better to use a Struct rather than a Hash in Ruby?

前端 未结 6 1226
清歌不尽
清歌不尽 2021-01-30 20:44

A Ruby Struct allows an instance to be generated with a set of accessors:

# Create a structure named by its constant
Customer = Struct.new(:name, :address)     #         


        
6条回答
  •  迷失自我
    2021-01-30 21:05

    I have rerun @mpospelov's benchmarks on Ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin20].

    Simple

    Warming up --------------------------------------
                    hash     1.008M i/100ms
                  struct   423.906k i/100ms
                 ostruct    16.384k i/100ms
    Calculating -------------------------------------
                    hash      9.923M (± 1.9%) i/s -     50.412M in   5.082029s
                  struct      4.327M (± 2.6%) i/s -     22.043M in   5.097358s
                 ostruct    158.771k (± 6.7%) i/s -    802.816k in   5.084066s
    
    Comparison:
                    hash:  9923144.6 i/s
                  struct:  4327316.1 i/s - 2.29x  (± 0.00) slower
                 ostruct:   158771.4 i/s - 62.50x  (± 0.00) slower
    

    Huge List

    Warming up --------------------------------------
                    hash    71.378k i/100ms
                  struct    99.245k i/100ms
                 ostruct   855.000  i/100ms
    Calculating -------------------------------------
                    hash    712.113k (± 4.9%) i/s -      3.569M in   5.024094s
                  struct      1.098M (± 2.9%) i/s -      5.558M in   5.066160s
                 ostruct      8.629k (± 4.8%) i/s -     43.605k in   5.066147s
    
    Comparison:
                  struct:  1098071.6 i/s
                    hash:   712112.5 i/s - 1.54x  (± 0.00) slower
                 ostruct:     8628.8 i/s - 127.26x  (± 0.00) slower
    

    Conclusion

    • If performance does matter, use struct.
    • If defining fields on the fly matters, go with open struct.

提交回复
热议问题