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

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 had some doubts about performance

  • Should I check the list before cleaning? ( .Any() ou .Count > 0 ? ) to not execute .Clear() unnecessarily? Or can If worse than Clear?

  • Move the list creation into the for? (I think it's less efficient, create an instance of the object with each loop.)

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

        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...
        }
    
  • asked by anonymous 12.02.2018 / 10:46

    2 answers

    7
      

    Leave as is, call clear without checking for content.

    The Clear method already does this, so coding it again would not make sense.

    link

    And as you said, creating the list at each iteration is less efficient.

        
    12.02.2018 / 12:51
    1

    Complementing the response that has already been given, you can use the Stopwatch to perform performance tests of the possibilities you have 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've placed a link code that can run on .Net Fiddle to see how it works.

        
    14.02.2018 / 21:00