I think, this is one of the most basic programming questions. And I have a seen a number of different answers for different languages. So I suppose this is language-specific, because unused variables should be treated differently...

Imagine I have a function that is called really a lot. Tens of times on each player's action.
For example it takes an array of KinematicBody2D elements, asks each one its position, and finds the geometrical center (average position.x, average position.y).

Now. For GDScript. Would it be wise to declare temporary variables inside the function every time it is called?
Or maybe it would be better to create few variables inside class and re-use them all the time from inside function?

I mean, if I declare local variables again and again so often, won't this affect performance? The engine would have to allocate memory all the time and then clear it, removing single-use variables again and again.

Sorry if this sounds not very clever.

  • kuligs2 and xyz replied to this.
  • Rainfollower Every var inside a function will do an allocation on each call and deallocation on exit. You may also have additional overhead related to the function call itself. If you want to optimize, best to get rid of the function completely. Allocate the vars outside of the iteration loop as having them inside the loop body will also do alloc/free on each step of the loop.

    Just make sure that the function is really affecting the performance in a significant way and that you're not trying to optimize prematurely. First profile your code as is. If the function is indeed the bottleneck and it gets called many times per frame - get rid of it.

    Rainfollower Isnt the compiler smart enough to optimize variable declarations? I havent measured, but i think modern day compiler are pretty smart for that.

    Rainfollower Every var inside a function will do an allocation on each call and deallocation on exit. You may also have additional overhead related to the function call itself. If you want to optimize, best to get rid of the function completely. Allocate the vars outside of the iteration loop as having them inside the loop body will also do alloc/free on each step of the loop.

    Just make sure that the function is really affecting the performance in a significant way and that you're not trying to optimize prematurely. First profile your code as is. If the function is indeed the bottleneck and it gets called many times per frame - get rid of it.