Which is faster: clear collection or instantiate new

后端 未结 8 968
遇见更好的自我
遇见更好的自我 2020-12-01 06:26

I have some number of generic lists in my code, that have tens or hundreds elements. Sometimes I need to refill this lists with other objects, so question is: what will be f

8条回答
  •  孤街浪徒
    2020-12-01 06:39

    I've run this test:

    private static void Main(string[] args)
    {
        int defaultN = 1000;
    
        Stopwatch sw = new Stopwatch();
    
        while (true)
        {
            Console.WriteLine("Enter test elements number:");
            int n;
            if (!int.TryParse(Console.ReadLine(), out n)) n = defaultN;
            else defaultN = n;
    
            Console.WriteLine($"Test with {n} elements");
    
            List list = Enumerable.Repeat(new object(), n).ToList();
            sw.Start();
            Clear(list);
            sw.Stop();
            Console.WriteLine("Clear: {0} ms", sw.ElapsedTicks / 10000D);
    
            GC.Collect();
            GC.WaitForPendingFinalizers();
    
            List list2 = Enumerable.Repeat(new object(), n).ToList();
            sw.Restart();
            Reinitialize(list2);
            sw.Stop();
            Console.WriteLine("Reinitialize: {0} ms", sw.ElapsedTicks / 10000D);
    
            GC.Collect();
            GC.WaitForPendingFinalizers();
    
            List list3 = Enumerable.Repeat(new object(), n).ToList();
            sw.Restart();
            ReinitializeAndCollect(list3);
            sw.Stop();
            Console.WriteLine("ReinitializeAndCollect: {0} ms", sw.ElapsedTicks / 10000D);
    
            Console.WriteLine("===");
        }
    }
    private static List Clear(List list)
    {
        list.Clear();
        return list;
    }
    private static List Reinitialize(List list) => new List();
    private static List ReinitializeAndCollect(List list)
    {
        list = new List();
    
        GC.Collect();
        GC.WaitForPendingFinalizers();
    
        return list;
    }
    
    
    

    My conclusion based on a results of my ordinary core i3 processor:

    In case of thousands of elements - it is better to clear list. It is fast and memory efficient.

    If collection has more than 100 000 elements - reinitializing becomes more attractive. If after profiling you think that there is a bottleneck here, use it. Re-initialization will be very fast, but as third method test shows, future garbage collecting will be about as slow as just clearing the list.

    So short answer is: if you didn't profiled your application, use Clear. Reusing objects is good. If you did - you already know what to do.

    提交回复
    热议问题