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

Asked

Viewed 213 times

8

There is a need to allocate null in the object after its use?

In the example below just after using the list I have a method that takes a lot of time to run. 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();
    }

2 answers

10

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

If the idea is to release memory, it won’t have any consequence either, it will only be released when the GC determines it’s the best time for it. Trying to force memory release can even cause performance losses.

8


In this case because the variable is local, it is destroyed at the end of the method. It might even be useful if this list is too large and if this FazAlgumaCoisaDemorada() need a lot of memory. Then it is likely that the GC would be triggered at some point in the middle of it and the ideal is that it can release as much memory as possible. But that’s a very specific and rare circumstance.

Do not do it "just in case". You have to test and see if you have the advantage and not cause other problems.

In most cases it will not affect the performance. Interestingly annulment can cause some delay because it makes it easier to have a garbage collection, but it will be a delay beneficial by the nature of the . NET GC.

It may 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, then it is better to release the referenced object. To do this the simplest way is to undo the variable.

Almost always when you need to override an instance or static variable, it is because something has been poorly architected.

The release of memory does not occur at the time of variable nullification, but when the garbage collector decides to work. And please, don’t force your call!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.