Optimizing member variable order in C++

前端 未结 10 681
长发绾君心
长发绾君心 2020-12-04 07:18

I was reading a blog post by a game coder for Introversion and he is busily trying to squeeze every CPU tick he can out of the code. One trick he mentions off-hand is to

10条回答
  •  醉梦人生
    2020-12-04 07:35

    I'm focusing on performance, execution speed, not memory usage. The compiler, without any optimizing switch, will map the variable storage area using the same order of declarations in code. Imagine

     unsigned char a;
     unsigned char b;
     long c;
    

    Big mess-up? without align switches, low-memory ops. et al, we're going to have an unsigned char using a 64bits word on your DDR3 dimm, and another 64bits word for the other, and yet the unavoidable one for the long.

    So, that's a fetch per each variable.

    However, packing it, or re-ordering it, will cause one fetch and one AND masking to be able to use the unsigned chars.

    So speed-wise, on a current 64bits word-memory machine, aligns, reorderings, etc, are no-nos. I do microcontroller stuff, and there the differences in packed/non-packed are reallllly noticeable (talking about <10MIPS processors, 8bit word-memories)

    On the side, it's long known that the engineering effort required to tweak code for performance other than what a good algorithm instructs you to do, and what the compiler is able to optimize, often results in burning rubber with no real effects. That and a write-only piece of syntaxically dubius code.

    The last step-forward in optimization I saw (in uPs, don't think it's doable for PC apps) is to compile your program as a single module, have the compiler optimize it (much more general view of speed/pointer resolution/memory packing, etc), and have the linker trash non-called library functions, methods, etc.

提交回复
热议问题