I'd just like to ask what's the difference in execution time when:
a) We have variables declared in main()
and send them in functions using arguments
b) We have global variables and access them directly from functions with no arguments
The thing is I started writing few aps and just saw a few discussions about this, but I haven't yet written any application that makes the difference bigger then few ms.
Passing parameters to function involves usually one of two assembler instructions: push param
(and later pop param
) or mov ax, param
. Since processor is able to do (a lot) more in a second, such "optimization" mostly probably will go unnoticed (a few ms on the whole program is below the error margin)
Using global variables in the place of function parameters will cause a huge mess in the code with almost unnoticeable or possibly no performance gain.
All of this depends on what CPU and compiler that are used.
When you pass a parameter to a function, one of the following could happen:
Using a global variable is will be ever so slightly faster than using the stack. It will unlikley be faster than using a CPU register: inside the function the value might need to be loaded into such a register before calculations anyhow.
It should be noted we are talking about a few CPU ticks here and there.
My advise:
Stack operations are very efficient, and they are made even more efficient because the stack is likely to be in cache memory. That could make using the stack even faster than not using it.
Expect parameter passed variables to be a lot faster than global variables. In Modern ABIs, function parameters are passed mostly using CPU registers which are immediately available to the CPU.
Global variables must be read from (static) memory. Worse than that, static memory is allocated on its own memory page, which is generally far from your stack (or heap) memory. This means that cache misses are more likely which in turn means that access can consume a large number of CPU cycles.
Obviously this depends a lot on your usage patterns.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.