Dictionary vs Object - which is more efficient and why?

后端 未结 8 798
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 15:55

What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?

Background: I have to load huge amount of data

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 16:35

    There is no question.
    You have data, with no other attributes (no methods, nothing). Hence you have a data container (in this case, a dictionary).

    I usually prefer to think in terms of data modeling. If there is some huge performance issue, then I can give up something in the abstraction, but only with very good reasons.
    Programming is all about managing complexity, and the maintaining the correct abstraction is very often one of the most useful way to achieve such result.

    About the reasons an object is slower, I think your measurement is not correct.
    You are performing too little assignments inside the for loop, and therefore what you see there is the different time necessary to instantiate a dict (intrinsic object) and a "custom" object. Although from the language perspective they are the same, they have quite a different implementation.
    After that, the assignment time should be almost the same for both, as in the end members are maintained inside a dictionary.

提交回复
热议问题