抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

数组栈、链表栈以及c#系统提供的Stack性能比对

代码如下

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace AlgorithmTest09_实现栈Stack
{
class Program
{
public static long TextStack(IStack<int> stack, int N)
{
Stopwatch t = new Stopwatch();
t.Start();
for (int i = 0; i < N; i++)
{
stack.Push(i);
}
for (int i = 0; i < N; i++)
{
stack.Pop();
}
t.Stop();
return t.ElapsedMilliseconds;
}
static void Main(string[] args)
{
#region 测试性能
//数组栈
int N = 10000000;
Array1Stack<int> array1Stack = new Array1Stack<int>(N);
long t1 = TextStack(array1Stack, N);
Console.WriteLine("array1Stack'Time:{0}ms", t1);

//链表栈
LinkedList1Stack<int> linked = new LinkedList1Stack<int>();
long t2 = TextStack(linked, N);
Console.WriteLine("linked'Time:{0}ms", t2);

//c#自带的stack
Stack<int> stack = new Stack<int>();
Stopwatch t3 = new Stopwatch();
t3.Start();
for (int i = 0; i < N; i++)
{
stack.Push(i);
}
for (int i = 0; i < N; i++)
{
stack.Pop();
}
t3.Stop();
Console.WriteLine("stack'Time:{0}ms", t3.ElapsedMilliseconds);
#endregion
Console.ReadKey();
}
}
}

打印结果

image-20221101160223033

可以看出系统自带的Stack性能最优

链表实现的栈性能最差,因为链表需要对节点和下一节点操作,更吃性能

评论