Should I store entire objects, or pointers to objects in containers?

后端 未结 10 2092
忘掉有多难
忘掉有多难 2020-11-27 09:31

Designing a new system from scratch. I\'ll be using the STL to store lists and maps of certain long-live objects.

Question: Should I ensure my objects have copy co

10条回答
  •  盖世英雄少女心
    2020-11-27 09:55

    This question has been bugging me for a while.

    I lean to storing pointers, but I have some additional requirements (SWIG lua wrappers) that might not apply to you.

    The most important point in this post is to test it yourself, using your objects

    I did this today to test the speed of calling a member function on a collection of 10 million objects, 500 times.

    The function updates x and y based on xdir and ydir (all float member variables).

    I used a std::list to hold both types of objects, and I found that storing the object in the list is slightly faster than using a pointer. On the other hand, the performance was very close, so it comes down to how they will be used in your application.

    For reference, with -O3 on my hardware the pointers took 41 seconds to complete and the raw objects took 30 seconds to complete.

提交回复
热议问题