最近项目有一个场景:在winfrom开发中,我需要实时监听一个Socket服务,并将读取字符内容展示到界面上。
最初我的实现方式是用static string 变量来在线程中共享改成员的值,但在界面展示的时候有很明显的延时,于是我就在思考是不是换一种数据结构延迟会好一些呢?有了这个想法之后马上操刀:代码示例如下:
private static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
#region string 测试结果0.1896ms
string tempStr = "";
for (int i = 0; i <= 1000; i++)
{
tempStr = i.ToString();
tempStr = "";
}
#endregion string 测试结果0.1896ms
#region 队列测试结果 执行用时: 0.03ms
//Queue queue = new Queue();
//for (int i = 0; i <= 1000; i++)
//{
// queue.Enqueue(i);
// queue.Dequeue();
//}
#endregion 队列测试结果 执行用时: 0.03ms
#region 栈测试结果 执行用时: 0.058ms
//Stack stack = new Stack();
//for (int i = 0; i <= 1000; i++)
//{
// stack.Push(i);
// stack.Pop();
//}
#endregion 栈测试结果 执行用时: 0.058ms
#region Int 测试结果 执行用时: 0.0059ms
//int tempIntValue = 0;
//for (int i = 0; i <= 1000; i++)
//{
// tempIntValue = i;
// tempIntValue = 0;
//}
#endregion Int 测试结果 执行用时: 0.0059ms
sw.Stop();
TimeSpan ts = sw.Elapsed;
string timeInteval = string.Format("执行用时: {0}ms", ts.TotalMilliseconds);
Console.WriteLine(timeInteval);
Console.ReadKey();
}
经本地环境测试,Int类型频繁操作是最快的,Queue,Stack相近,String频繁操作最慢。因此再开发中要尽量避免频繁的进行字符串的拼接。