Optimize by Variable Organization (Packing Data)
![]() |
Most of us when we are writing code either do not think of how we organize our variable declarations or will organize the variable declarations into readable and logical groups. However, for an easy way to optimize one’s code one can use a suggested method within Game Engine Architecture by Jason Gregory |
Within chapter 3.2.5 he describes a method of declaring the variables of a class (or structure) where the variables with the greatest size is declared first. This method will pack usable content of memory in a tighter fit with less fragmentation.
Remember this is an easy form of optimization. Although I use this method of organizing my class variables it is a valid argument to organize one’s variables into readable and logical groups. However, be aware by packing memory the greatest benefit isn’t saving space within RAM (and/or the stack) the greatest benefit of this method is processing speed (for those game developers out there).When the CPU requires access to a variable (in short) the variable and the surrounding memory is copied into the CPU’s cache. If the next variable the CPU requires is within it’s cache then there is no need to access RAM once again and thus saving time. If there is inefficient packing of the data then the CPU will access the data within RAM more often. As a side note there are microprocessors out there that force the issue of aligned data. By practicing packing of data will save possible headaches if developed code is ported for use on another machine; for example the PlayStation 2.You can also argue another good practice is padding one’s structures and although I do see the need of padding on some hardware (like the PlayStation 2) it is a maintenance nightmare within a team (of relaxed developers). So I advise using and implementing padding when necessary. Padding is when a developer adds an array of bytes to the end of a class or structure to force alignment. For example:
Please, keep your comments family friendly and respectful of each other and the author.