I've been programming with Java for Android quite some while now. Since performance is very important for the stuff I am working on I end up just spamming global variables. I guess everyone will come rushing in now and tell me this is the worst style ever, but lets keep it simple. For Android, local variables means garbage collection and garbage collection is something that kills performance.
Lately I have started using the NDK. Now I feel the urge to actually take all the local variables and change them to global variables. I am wondering though if this makes any sense in c code. Obviously it is no good style, but if it is needed for speed I'll sacrifice the style gladly.
I've looked through older threads about local vs global, but I haven't been able to find anything about speed. So my question is, if I am calling a function very often is it relevant for the speed that local variables are created and die after the function is done? Or doesn't it matter at all and I can happily keep on using the local variables.
I would test it myself, but for some reason the performance of my app goes up and down like a roller coaster and I doubt I'll be able to really make any sense of the data. I hope someone can help me out before I rewrite my whole code for nothing :)
It all depends on the scope of the variable. If you feel that a certain variable will take multiple values by passing through various functions then use local variables and pass them in function calls. If you feel that a certain variable you need to use will have constant value, then declare it as a global variable.
Global variables can be accessed by all the functions present in the program. Only a one-time declaration is required. Global variables are very useful if all the functions are accessing the same data.
A global variable can have no access control. It can not be limited to some parts of the program. Using global variables causes very tight coupling of code. Using global variables causes namespace pollution.
It is usually not a good programming practice to give different variables the same names. If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.
For Android, local variables means garbage collection...
This is an incorrect statement. Local variables are allocated on the stack - not dynamically allocated on the heap.Check out this article on what gets allocated where in Java
As a rule, items allocated on the stack do not require garbage collection/freeing and "die" immediately after the execution leaves its current scope. Stack allocation/deallocation is significantly faster than heap allocation and garbage collection.
Try to avoid global variables for both style and performance reasons. Stack-allocated local variables will perform much faster.
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