Do I need to assign null to a variable after use?

7

Is there a need to assign null to the object after its use?

In the example below right after using the list I have a method that takes a long time to run. Do I need to assign null to the list to optimize the application?

private void Exemplo()
    {
        List<Cliente> listaClientes = ObterClientes();

        foreach (Cliente cliente in listaClientes)
        {
            SalvarClientes(cliente);
        }

        // Preciso fazer isto?
        listaClientes = null;

        FazAlgumaCoisaDemorada();
    }
    
asked by anonymous 20.01.2017 / 17:35

2 answers

8

In this case because the variable is local, it is destroyed at the end of the method. It could even be useful if this list is too large and if that FazAlgumaCoisaDemorada() needs too much memory. It is likely that the GC would be triggered sometime in the middle of it and ideally it can release as much memory as possible. But this is a very specific and rare circumstance.

Do not make "just in case." have to test and see if it has an advantage and does not cause other problems.

In most cases it will not affect performance. Curiously, canceling may cause some delay because garbage collection is easier, but will be a beneficial delay for the .NET GC nature.

It can be useful in some case where the variable is static or is part of an object that must remain alive for a long time and does not want to keep alive the object it refers to, it is better to release the object referenced. To do this the simplest way is to undo the variable.

Almost always when you need to undo an instance variable or static, it's because something was poorly architected.

The memory release does not occur when the variable is canceled, but when the garbage collector resolves to work. And please do not force your call !

    
20.01.2017 / 17:56
9

The answer is no, it has no effect on performance.

If the idea is to free memory, it will also have no consequence, it will only be released when the GC determines that it is the best time to do so. Trying to force the memory release may even lead to performance loss.

    
20.01.2017 / 17:43