1
votes

I have a baseclass named GameObject from which other classes derive. I am wondering if handling the memory allocation by allocating all derived classes of GameObjects in contiguous memory will improve performance.

I will end up iterating over all of them each game engine frame.

My question is, does contiguous memory storage in this case give me faster iteration times than mallocing memory without contiguation? In both cases, I have to keep a vector of pointers to the Game Objects since they will vary in size.

2
It will probably improve the performance, at least a bit. Remember the golden rule though, don't optimize before profiling. If you think that is a source of cache misses, you can always overload the operator new of your classes. - enobayram
Using contiguous memory could improve cache hit ratio, so your code might become faster. Yet until you do some profiling it would remain just another case of premature optimization. - Sergey Kalinichenko

2 Answers

0
votes

Iterating through objects in continuous memory likely works better because cache and locality. However, I recommend that you build the two systems and actually profile them. Good luck!

0
votes

I'm not sure I understand the question. Are you asking if its better to pre-allocate all your objects in one giant block of memory and store the pointers to subsections of that in memory? If so please don't do that.

Instead of being faster you're more likely bound to slow things down since the system has to request contiguous memory of larger blocks instead of non-contiguous of smaller blocks. Keep in mind block allocation, paging, etc. You may request 100 megabytes of contiguous memory but its really not contiguous. A bunch of it is in disk and everything is broken up into pages anyways.

Then you're faced with the question of do you allocate all your GameObjects in one go to get contiguous memory or are you creating them on demand? Do you really want to pre-allocate for this one minor optimization? What happens if you need to create a new object and your contiguous memory block wasn't large enough? etc.

Really I'm just brainstorming potential problems here. Like the other comments said its a case of premature optimization.

Now, it would certainly be faster if you stored all your pointers in a contiguous array instead of a vector which grows and copies based on its current size, but even then unless you absolutely know the amount of game objects you're better off just allocating a sufficiently large vector so that it only grows once or twice.