Which one is more efficient : List or int[]

后端 未结 6 1141
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 08:30

Can someone tell me which one is more efficient between List and int[]. Because I am working on a project and as you might know efficien

6条回答
  •  萌比男神i
    2020-12-09 09:09

    Just for the fun of it, I ran this:

    int cap = 100000;
    
    Stopwatch sw1 = new Stopwatch();
    sw1.Start();
    
    int[] ix = new int[cap];
    for (int x = 0; x < cap; x++)
    {
        ix[x] = 1;
    }
    
    sw1.Stop();
    
    Stopwatch sw2 = new Stopwatch();
    sw2.Start();
    List iy = new List(cap);
    for (int y = 0; y < cap; y++)
    {
        iy.Add(y);
    }
    sw2.Stop();
    
    Console.WriteLine(cap.ToString() + "     int[]=" + sw1.ElapsedTicks.ToString());
    Console.WriteLine(cap.ToString() + " List=" + sw2.ElapsedTicks.ToString());
    
    Console.ReadKey();
    

    And got this:

    100000 int[]=1796542
    100000 List=2517922
    

    I tried it in elapsed milliseconds and got 0 and 1 respectively. Clearly the int[] is way faster, but unless you're talking huge arrays, I'd say it is just nominal.

提交回复
热议问题