When should I use Struct vs. OpenStruct?

后端 未结 9 1182
孤城傲影
孤城傲影 2020-11-28 00:35

In general, what are the advantages and disadvantages of using an OpenStruct as compared to a Struct? What type of general use-cases would fit each of these?

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 01:17

    OpenStructs use significantly more memory and are slower performers versus Structs.

    require 'ostruct' 
    
    collection = (1..100000).collect do |index|
       OpenStruct.new(:name => "User", :age => 21)
    end
    

    On my system the following code executed in 14 seconds and consumed 1.5 GB of memory. Your mileage might vary:

    User = Struct.new(:name, :age)
    
    collection = (1..100000).collect do |index|
       User.new("User",21)
    end
    

    That finished nearly instantaneously and consumed 26.6 MB of memory.

提交回复
热议问题