(精华)2020年8月27日 数据结构与算法解析 Stack和List性能分析

72 阅读1分钟
//内存连续线性表,查询上面时间复杂度为O(1)
public void List()
{
    List<TestModel> test = new List<TestModel>();
    for (int i = 0; i < 10_000; i++)
    {
        test.Add(new TestModel()); //进的速度和stack进速度一样
    }

    for (int i = 0; i < 10_000; i++)
    {
        //list出是以尾部为标准
        test.RemoveAt(0);//出的速度比stack出大太多
        test.RemoveAt(test.Count);//出的速度和stack出的速度一样
    }
}

//内存不连续,在查询上面时间复杂度为O(n)
public void Stack()
{
    Stack<TestModel> test = new Stack<TestModel>();
    for (int i = 0; i < 10_000; i++)
    {
        test.Push(new TestModel()); 
    }

    for (int i = 0; i < 10_000; i++)
    {
        test.Pop();
    }
}