当前位置:网站首页>C # custom stack
C # custom stack
2022-07-23 12:43:00 【LKZ kumuzi plum】
C# Custom stack
Performance follow C# It's better to bring it with you
Implemented iterators 、 serialize 、 Deserialization, etc !
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace LKZ.DataStruct
{
/// <summary>
/// Stack
/// First in, then out
/// Last in, first out
/// </summary>
[Serializable]
public class Stack<T> : IReadOnlyCollection<T>, ISerializable, IDeserializationCallback, IEnumerable<T>, IEnumerable, IEnumerator<T>, IEnumerator, ICollection
{
/// <summary>
/// The capacity of the array
/// </summary>
public int Capacity {
get; private set; }
/// <summary>
/// How many elements does the array now have
/// </summary>
public int Count {
get; private set; }
public object Current => array[position];
T IEnumerator<T>.Current => array[position];
public object SyncRoot => throw new NotImplementedException();
public bool IsSynchronized => false;
/// <summary>
/// Deserialization requires this parameter to store the deserialized type
/// </summary>
private SerializationInfo info;
/// <summary>
/// Array
/// </summary>
private T[] array;
/// <summary>
/// The display position of the iterator
/// </summary>
private int position;
/// <summary>
/// structure
/// The initialization capacity of the default array is 10
/// </summary>
public Stack()
: this(10)
{
}
/// <summary>
/// structure
/// </summary>
/// <param name="capacity"> The capacity of array initialization </param>
public Stack(int capacity)
{
array = new T[capacity];
Capacity = capacity;
Count = 0;
}
/// <summary>
/// Construction of deserialization call
/// </summary>
/// <param name="info"> Deserialization requires this parameter to store the deserialized type </param>
protected Stack(SerializationInfo info, StreamingContext context)
: this(10)
{
this.info = info;
}
/// <summary>
/// Look at the elements of the head , Do not remove the stack
/// </summary>
/// <returns> Returned element </returns>
public T Peek()
{
if (Count == 0)
ThrowError(" The element in the stack is empty , There is no way to check ");
return array[Count - 1];
}
/// <summary>
/// Remove the element that returns the header
/// </summary>
/// <returns> Returned element </returns>
public T Pop()
{
if (Count == 0)
ThrowError(" The element in the stack is empty , There is no way to take it out ");
T temp = array[--Count];
array[Count] = default(T);
// Shrinkage capacity
// If the capacity is less than the number of data 4 Divided 1, Just shrink the capacity by half
if (Count <= Capacity / 4)
ResetCapacity(Capacity / 2);
return temp;
}
/// <summary>
/// Add an element to the header
/// </summary>
/// <param name="value"> Values to be added </param>
public void Push(T value)
{
array[Count++] = value;
// Capacity expansion
if (Count == Capacity )
ResetCapacity(Capacity * 2);
}
/// <summary>
/// Serialize the callback method
/// </summary>
/// <param name="info"> The data to be serialized needs to be stored here and returned </param>
/// <param name="context"></param>
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
ThrowError("info It's empty ");
if (Count != 0)
{
T[] array = new T[Count];
CopyTo(array, 0);
info.AddValue("data", array, array.GetType());
}
}
/// <summary>
/// Deserialize the callback method
/// </summary>
/// <param name="sender"> Who called this deserialization </param>
void IDeserializationCallback.OnDeserialization(object sender)
{
if (info == null)
ThrowError("info It's empty ");
array = (T[])info.GetValue("data", typeof(T[]));
Count = array.Length;
Capacity= Count;
}
public IEnumerator<T> GetEnumerator()
{
Reset();
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
Reset();
return this;
}
public bool MoveNext()
{
return ++position < Count;
}
public void Reset()
{
position = -1;
}
public void Dispose()
{
}
public void CopyTo(Array array, int index)
{
if (array == null)
ThrowError("Array Array is empty ");
else if(index<0||index>Count)
ThrowError(" The index is not standardized ");
Array.Copy(this.array, index, array, index, Count-index);
}
/// <summary>
/// Reset capacity
/// </summary>
/// <param name="newCapacity"> New capacity </param>
private void ResetCapacity(int newCapacity)
{
T[] newArr = new T[newCapacity];
Array.Copy(array, newArr, Count);
array = newArr;
Capacity = newCapacity;
}
/// <summary>
/// Throw an exception
/// </summary>
/// <param name="message"></param>
private void ThrowError(string message)
{
throw new AggregateException(message);
}
}
}
Now take the customized Stack Stack and C# Performance comparison of the built-in stack
stay Release Compare in mode
The following is the code for comparison , Add to stack 90000000 Elements , Comparison time
// test ,90000000 Add data again , Test performance
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Stack<int> ss = new Stack<int>();
for (int i = 0; i < 90000000; i++)
{
ss.Push(i);
}
stopwatch.Stop();
Console.WriteLine(" Their own Stack Stack :"+stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
System.Collections.Generic. Stack<int> saas = new System.Collections.Generic.Stack<int>();
for (int i = 0; i < 90000000; i++)
{
saas.Push(i);
}
stopwatch.Stop();
Console.WriteLine("C# Of Stack Stack :" + stopwatch.ElapsedMilliseconds);
Comparing the results 
According to the above display , Customized stack performance ratio C# It's a little better
Pay attention to WeChat public number 【 Prodigal monologue 】 Get more !
边栏推荐
猜你喜欢

表格个人简历

OSI开放系统互联模型和TCP/IP模型
![[AUTOSAR DCM 1. module introduction (DSL, DSD, DSP)]](/img/99/55b3162ad061fbd00145d0b6810592.png)
[AUTOSAR DCM 1. module introduction (DSL, DSD, DSP)]

InheritableThreadLocal与阿里的TransmittableThreadLocal设计思路解析

Using one-way linked list to realize queue

MySQL性能优化,索引优化

【读书笔记《凤凰架构》- 构架可靠的大型分布式系统.周志明】(一)
![[fee of AUTOSAR (difference between nonvolatile memory flash and EEPROM)]](/img/cc/34bfcc450d82befab24173b0cb132d.png)
[fee of AUTOSAR (difference between nonvolatile memory flash and EEPROM)]

HCIP --- HDLC和PPP协议

Unity3D高清渲染管线无法在模型上播放视频
随机推荐
GameFramework:Resource加载,资源加载,依赖加载,任务池,对象池,引用计数
C语言:基于顺序表的学生管理系统,超级详细,全部都有注释,看完不懂来扇我。
unity3d:Assetbundle模拟加载,同步加载,异步加载,依赖包加载,自动标签,AB浏览器,增量打包
hot 100深度优先
如何用普通的文本编辑器写Web页面
[bootloader architecture and brushing process based on UDS service]
浅析UDP协议和TCP协议
基于UDP的群聊聊天室
剑指offer 青蛙跳楼梯
C语言:详细讲解基于tcp和udp的两种本地通信方式
0数组 LeetCode605. 种花问题
详解TCP的交互数据流和成块数据流
C# 自定义双向链表
Mutual implementation of queue and heap (pure C implementation)
Related repo of synthetic Chinese recognition dataset
Vs attribute configuration related knowledge
MySQL性能优化,索引优化
主机字节序的判定
Analyze redis cluster
剖析Redis服务器