zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【愚公系列】2021年11月 C#版 数据结构与算法解析 Stack和List性能分析

2023-04-18 14:26:43 时间
//内存连续线性表,查询上面时间复杂度为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();
    }
}