When I profile my apps, I make sure that the code like this one:

private void Update(){
    int count = GetEnemyCount();

get's converted to this one:

private int count;
private void Update(){
    count = GetEnemyCount();

to prevent memory allocation and the heap expansion.

But what about the static methods, and allocations inside them?

Let's take this example (and assume I call it in Update()):

public static float GetPercentPositionX(Transform transform)
    float result;
    int screenWidth = GetScreenWidth();
    // some operations, result allocation, screenWidth usage
    return result;

What do I do here? Does it behave like a non-static function and expands the memory?

Shouldn't I declare static variables inside that class, to allocate the heap space at the start, for vars: result & screenWidth, just like I do in classic, non-static ones?

  • 1
    \$\begingroup\$ What leads you to believe that int count = GetEnemyCount() causes heap expansion? \$\endgroup\$
    – DMGregory
    Commented Feb 8, 2018 at 14:56

1 Answer 1


Local variables are not added to the heap. They are pushed onto the stack and immediately popped off the stack when they leave scope, thus already avoiding the heap (and the sort of memory allocation you are worried about) altogether. This is better memory management than what you are doing because your variables take up space on the heap when they don’t have to at all.

In short, you shouldn’t perform this optimization at all.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .