Jump to content
  • Advertisement
Sign in to follow this  
Twinblad3r

new array

This topic is 3777 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Why should we use new array? class CTest { public: float a; }; int main() { CTest *Test = new CTest[4] CTest Test[4]; delete [] Test; return 0; } Is it because accessing member variables are faster when new than creating object(s)? e.g. Test[0]->a; Test[0].a; I read that new without a memory pool is slow too... Thanks~

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by Twinblad3r
Why should we use new array?


new [] is useful when you are developing a container object, and need to create memory on-the-fly. However, as with all memory manipulation, it's very hard to use it right. Therefore, for any other purposes than developing a container, you should not use new [], but instead rely on existing containers to do the work. In the vast majority of cases, you can replace new [] with an std::vector.

Quote:
Is it because accessing member variables are faster when new than creating object(s)?
e.g. Test[0]->a; Test[0].a;

I read that new without a memory pool is slow too...


I would suggest that you don't care about it. But if you must care, new (in C++ only) is a slow operation that requires walking through a complex data structure to obtain the required memory (this can be accelerated by overloading operator new for certain types to return memory from a pool). It should be avoided when not necessary (just like any other kind of dynamic allocation).

Memory access does not care about where the data is, as long as it is close by. That is, accessing elements that are close to each other is fast (due to caching) while accessing elements that are sparse is slow. This is only noticeable if you do a lot of accesses at the same time (on the range of a few hundred consecutive accesses).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!