Do global variables mean faster code?

后端 未结 14 1980
情深已故
情深已故 2020-12-24 00:58

I read recently, in an article on game programming written in 1996, that using global variables is faster than passing parameters.

Was this ever true, and if so, is

14条回答
  •  误落风尘
    2020-12-24 01:36

    It might still be true, under some circumstances. A global variable might be as fast as a pointer to a variable, where its pointer is stored in/passed through registers only. So, it is a question about the count of registers, you can use.

    To speed-optimize a function call, you could do several other things, that might perform better with global-variable-hacks:

    • Minimize the count of local variables in the function to a few (explicit) register variables.
    • Minimize the count of parameters of the function, i.e. by using pointers to structures instead of using the same parameter-constellations in functions that call each other.
    • Make the function "naked", that means that it does not use the stack at all.
    • Use "proper-tail-calls" (does neither work with java/-bytecode nor java-/ecma-script)
    • If there is no better way, hack yourself sth like TABLES_NEXT_TO_CODE, which locates your global variables next to the function code. In functional languages this is a backend-optimization that uses the function-pointer as data-pointer, too; but as long as you do not program in a functional language, you only need to locate those variables beside those used by the function. Then again, you only want this to remove the stack-handling from your function. If your compiler generates assembler code that handles the stack, then there is no point in doing this, you could use pointers instead.

    I've found this "gcc attribute overview": http://www.ohse.de/uwe/articles/gcc-attributes.html

    and I can give you these tags for googling: - Proper Tail Call (it is mostly relevant to imperative backends of functional languages) - TABLES_NEXT_TO_CODE (it is mostly relevant to Haskell and LLVM)

提交回复
热议问题