Will using global variables give a speed up? In Intel's Architecture Software Developer Manual (about the microprocessor) it is recommended to use local variables instead of global. But, consider the following code:
void process_tcp_packets(void) {
char tcp_data[128];
do some stuff with the tcp_data[]....
}
void process_udp_packets(void) {
char udp_data[128];
do some stuff with the udp_data[]
}
void main_event_loop(void) {
while(1) {
if (pending_tcp_requests) {
process_tcp_packets();
}
if (pending_udp_requests) {
process_udp_packets();
}
}
}
When main_event_loop() is executed, the control of the flow depends on the variables "pending_tcp_requests" and "pending_udp_requests". Both functions process_tcp_packets() and process_udp_packets(), when called, will allocate local variables at the current stack pointer. This means if the code is constantly switching both functions, the local variables will be allocated at the same memory address. Sharing the memory address between both functions will evict data from current L1 cache and slow execution. So, by using global variables instead of local ones we can speed up execution. Is it correct or not?
If so, is there any drawback for using global variable in this case?
Global variables are very unlikely to give you a benefit over the stack in this case.
Sharing the memory address between both functions will evict data from current L1 cache and slow execution. So, by using global variables instead of local ones we can speed up execution. Is it correct or not?
Your premise is not correct for single-threaded use of memory.
Sharing the same memory between threads using different CPU caches will cause cache contention (and usually flushing). Sharing memory between functions on the same thread using the same CPU cache will not do this at all.
Also, on some platforms, local variables require less instructions to access than global variables (as they are offsets local to the stack pointer and can usually be encoded in <=2 bytes, where as global variables may not be).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With