In the tutorials I see var declared inside functions which are called every frame, it’s nice for code readability but isn’t it better perf wise to declare them outside the function so they get allocated at startup ?
Variables are not necessarily allocated. In a Jit compiled language that supports structs like C# or our JavaScript, they get allocated on the stack. Eg. Floats, ints, Vector3 all get allocated on the stack which is a lot faster than loading it from class variables. If it’s a real class then yes, allocating a variable has some overhead. But again it depends on the specifics, Eg. strings might get interned (internally reused) by the compiler.
Thanks,
When you say declared on the stack you mean that first time the script runs, it declares what’s needed and skip other var in the loop? So in essence doing something like
function Fire ()
{
private var hit : RaycastHit;
...
is as fast as ?
private var hit : RaycastHit;
function Fire ()
{
...
What if the code gets disabled in between shooting (like the uber awesome FPS tutorial) ? Does the var get re allocated on the stack when the script gets re-launched ?
By the way, how do you say “Unity is da bomb” in Danish [EDIT:] German?
In this specific case, RaycastHit is a struct, thus will be allocated on the stack and thus will be faster to keep as a local variable.
Generally it is better code style to keep local variables local, as it introduces fewer dependencies and thus makes code easier to read, so for clarity it is better to use local variables. If you know you are bound by allocation in some specific cases, caching makes sense but the default should be to keep things local, especially structs or builtin types like int, floats.
Thanks Joachim.
And about my second question ?
The stack doesn’t really allocate, well ok it does in a way but it’s really really cheap, almost for free. Certainly cheaper than accessing a member variable which internally will have to look up a pointer.
It’s kind of complicated to explain the exact performance characteristics without a having a low level knowledge about assembler and C++.
Thanks for the in-depth - it really helps, I was actually talking of the OTHER question:
"
By the way, how do you say “Unity is da bomb” in Danish [EDIT:] German?
"
Seriously, I just started using Yields and found out that you can enable a disabled script by sending a message to one of its function … this is pure genius!
To explain the difference between allocating on the stack, and allocating a class - allocating a class is dynamic allocating which is done at run-time, while allocating on the stack isn’t (and much cheaper).
Now I see quite a lot of undeclared variables that are being associated to a value:
a = 1;
b = 10;
something = a+b;
without any var in front of them – does it have any impact on performance?