• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
programci_84

[C++] Custom containers vs STL

6 posts in this topic

Hi all,

I want to write my own container classes and I've some questions.

I've learnt that when we want to add one or more elements to an STL container (e.g. std::vector), it increases the size of the buffer more than we want. For example, if we have a 4-element-vector and if it's capacity is 4, when we want to insert 3 elements somewhere in it, it sets the capacity (or size, whatever you say) more than 7 (e.g. 10). I think this is done to avoid calling ::operator new frequently. But the size increases unnecessarily, right?

So, for an STL-like custom container, which one is more expensive?:
a) Using new/delete every time we want to add/delete elements (To keep the size of the buffer exact: for an n-element-buffer, the size is n*sizeof(element_type) ).
b) Increasing the capacity unnecessarily (To avoid calling ::operator new and ::operator delete every time).

btw, I've heard about "heap compaction" but I don't have any idea about that.

Hope I could describe.

Thx in advance.
-R
0

Share this post


Link to post
Share on other sites
As Hodgman already explained, the capacity of vectors can indeed be controlled.

If you're looking to build a "custom" container that works for all possible use cases, you won't be able to do better than vector.

However, if you have a specific use case you need to optimize for, there might be a better way.

Now, to answer your actual question:

> a) Using new/delete every time we want to add/delete elements (To keep the size of the buffer exact: for an n-element-buffer, the size is n*sizeof(element_type) ).

This is most likely the worst possible solution. Keep in mind that new/delete are usually pretty expensive operations and that you need to copy the complete content of your container on every resize. If you're worried about memory wasting and do not need continuity in memory, you should consider making a vector of (smart) pointers to your element type. In this case, not much memory is wasted, because pointers are small and resizing is cheap, because the big / expensive to copy objects don't have to be moved.

> b) Increasing the capacity unnecessarily (To avoid calling ::operator new and ::operator delete every time).

That's exactly what vector is doing. Not only does it avoid new/delete, but also copying stuff around on resize.

I hope that helps!
1

Share this post


Link to post
Share on other sites
The reason why vector does that is performance. Essentially if instead of just resizing to the exact size you multiply the size by a factor, inserting lots of elements has asymptotically/amortized linear complexity (as opposed to n square). So that behavior isn't unnecessary at all. It is a choice that prioritizes algorithmic complexity over tight memory usage. Which is a very sensible choice given in a lot of cases you are not on ultra tight memory budgets.
1

Share this post


Link to post
Share on other sites
[quote name='programci_84' timestamp='1330582559' post='4918097']
So, for an STL-like custom container, which one is more expensive?:
a) Using new/delete every time we want to add/delete elements (To keep the size of the buffer exact: for an n-element-buffer, the size is n*sizeof(element_type) ).
b) Increasing the capacity unnecessarily (To avoid calling ::operator new and ::operator delete every time).
[/quote]

As mentioned previously, STL's vector is designed to optimize for access speed and insertion speed. Avoiding new and delete every time is not quite the whole picture for the reasoning of its memory allocation behavior. The main cost in vector's insertion is when a reallocation is made, the container maintains the old elements and appends the new one after the old elements in the newly allocated block. You need to copy all of those old elements from the old memory block to the new one.

This is where the O(n) cost comes from if you reallocate a constant size larger than the old memory block. When you increase the memory block size by a geometric factor, you can achieve an amortized constant time insertion because you end up performing the super expensive memory block copy far less frequently.
0

Share this post


Link to post
Share on other sites
It does more than just reduce the number of copies that occur duing the relocation involved in growing, it changes the insertion time from O(n) to amortized constant time i.e. O(1).
Consider the number of copies done to insert 512 items for a vector that doubles in size, starting at 8 items (real-world typical numbers).
To insert the 9th item, the capacity goes from 8 to 16 and the 8 existing items must be copied over...
To insert the 17th item, the capacity goes to 32 and 16 items must be copied over...
To insert the 33rd item 32 items must be copied over...
To insert the 65th item 64 items are copied over...
To insert the 129th item 128 items are copied...
To insert the 257th, 256 are copied...
The remainder require no growing.
Total number of copies for all 512 inserts: (8+16+32+64+128+256) = 504 (approximately the same number of items that were inserted!)

Growing by 1 each time instead gives you:
1+2+3+4+5+6+7+8+9+10+11+12+....511 copies, which equals 131072 copies. That's a boatload of copies, and it only gets rapidly worse.
If you want 100000 items - forget it, that's 5 billion copies required!!

But wait there's still more; Growing by a geometric factor (e.g doubling) also reduces memory fragmentation.

Forget about the fact that a vector allocates more memory than it often uses at any given moment. As that memory has not been touched yet it has not had to be fetched or cached, and it makes no difference whether the memory allocator itself reserves that extra room, or whether the container does it. I'm told this is especially true on Linux where allocated memory isn't even mapped to physical memory until it is touched.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0