Performance of Arrays and Hashes in Ruby

后端 未结 4 1419
旧巷少年郎
旧巷少年郎 2020-11-29 18:39

I have a program that will store many instances of one class, let\'s say up to 10.000 or more. The class instances have several properties that I need from time to time, but

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 19:30

    1. Use a Set of Documents. It has most of the properties you want (constant-time lookup and does not allow duplicates),. Smalltalkers would tell you that using a collection that already has the properties you want is most of the battle.

    2. Use a Hash of Documents by document id, with ||= for conditional insertion (rather than has_key?).

    Hashes are designed for constant-time insertion and lookup. Ruby's Set uses a Hash internally.

    Be aware that your Document objects will need to implement #hash and #eql? properly in order for them to behave as you would expect as Hash keys or members of a set, as these are used to define hash equality.

提交回复
热议问题