What is the most efficient way to clear a list (List) with C#?

Asked

Viewed 2,197 times

2

I have a scenario here where I create a list to check some items, and I need to clear this list inside the loop, and I got some questions regarding the performance

  1. I must check the list before I clean up ? ( .Any() ou .Count > 0 ?) not to execute the .Clear() no need? Or If may be worse than Clear ?

  2. Move list creation into for? (I think it’s less
    efficient, create an object instance at each loop.)

  3. Leave as is, call the clear without checking if the list there content.

        var gameIds = new List<int?>();
        var gameId = gameSession?.GameId % 100000;
    
        for (int i = 0; i < Messages.Count; ++i)
        {
            var message = Messages[i];
    
            gameIds.Clear();
    
        //.... mais código...
        }
    
  • Before you think of the most efficient way to clear the list, write the code that does what you need. When you have that code and it works, run your project and use a profiler to see if that piece of code is even a problem. Premature optimization is a problem because you think it’s solving a problem that may not actually even exist.

  • The code is ready and is going into production, I was asked here if it would be better to clear this list or not before performing the check. Sorry if I was unclear in the content of the question. Thank you.

2 answers

7


  • 1

    Excellent master! That’s exactly what I was looking for, that level of detail :)

  • 2

    Here is a test for you to see the times of every possibility you have raised.

  • 1

    Excellent sharing of source code mscorelib, great reference!

  • top too , thanks Pagotti

  • @Pagotti puts a reply with this link here, will be useful for future queries.

1

Complementing the answer already given, it is possible to use the class Stopwatch to perform performance tests of the possibilities you raised.

For example:

public class Program 
{
    public static void Main() 
    {

        Medir(ListaCheia, "Lista Cheia");
        Medir(ListaVazia, "Lista Vazia");
    }

    public static void Medir(Action action, string Descricao) 
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        action();
        stopwatch.Stop();
        WriteLine($"Tempo: {stopwatch.Elapsed} : {Descricao}");
    }

    public static void ListaCheia() 
    {
        List<int?> lista = new List<int?>();
        for(var i = 0; i < 100000; i++)
            lista.Add(i);
        lista.Clear();
    }

    public static void ListaVazia() {
        List<int?> lista = new List<int?>();
        lista.Clear();

    }
}

I put a code at that link that you can run on . Net Fiddle to see how it works.

Browser other questions tagged

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