- Home /
Do any variables declared within methods generate memory allocation?
Let's say there is a method that takes a parameter, like int MyMethod(int value) and it then does some math to return a variable like if(value - someValue < someOtherValue) { return int someNewValue; } would it allocate memory each time someNewValue is returned?
I'm wondering if you have created a private int at the top of the class it only allocates memory once, while this does every time it's called, which is what I thought made sense... Can anyone confirm or deny that? Perhaps unity knows to just keep ahold of someNewValue and edit it, rather than create a new variable each time something is returned by this method.
Answer by Eric5h5 · Nov 30, 2014 at 06:28 AM
I'm wondering if you have created a private int at the top of the class
Don't do that; it's bad programming. Only declare variables inside functions, unless they specifically need to be shared with other functions. Anyway, it depends, but primitive types such as int are (generally) declared on the stack, not the heap, so there's no GC. Local variables typically perform slightly better, and as I mentioned global variables are not good programming practice unless you actually need them, so avoid that; you won't be optimizing anything (but rather the opposite).
Your answer
Follow this Question
Related Questions
scriptableObject as database "a question about memory" 1 Answer
Should GetComponent() generate garbage when the component is not found? 1 Answer
Questions About Allocations - Arrays - Structs and so on 1 Answer
How can code generate memory garbage without instantiating any memory? 4 Answers
"stream from disc" WAV/AIFF file allocates tons of memory 0 Answers