【发布时间】:2021-07-10 11:38:27
【问题描述】:
哈希集测试经过时间:5.38
Linq 测试经过的 ime:0.64
Foreach 循环测试 Elapsed ime:0.32
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace _08_ArrayCheck
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
var a = Enumerable.Range('a','z'-'a'+1).Select(c=>(char)c).ToArray();
double sTime = 0;
double fTime = 0;
sTime = sw.Elapsed.TotalMilliseconds;
Hashset(a,'a');
fTime = sw.Elapsed.TotalMilliseconds;
Console.WriteLine("Hashset test Elapsed time:"+string.Format("{0:0.##}",(fTime-sTime)));
sTime = sw.Elapsed.TotalMilliseconds;
Linq(a,'a');
fTime = sw.Elapsed.TotalMilliseconds;
Console.WriteLine("Linq test Elapsed ime:"+string.Format("{0:0.##}",(fTime-sTime)));
sTime = sw.Elapsed.TotalMilliseconds;
Foreachloop(a,'a');
fTime = sw.Elapsed.TotalMilliseconds;
Console.WriteLine("Foreach loop test Elapsed ime:"+ string.Format("{0:0.##}",(fTime-sTime)));
sw.Stop();
}
public static bool Hashset(char[] a, char x)
// isn't hashset supposed to be'faster code performance wise
{
HashSet<char> hashSearch = new HashSet<char>(a);
return hashSearch.Contains(x);
}
public static bool Linq(char[] a, char x)//linq solution
{
return a.Contains(x);
}
public static bool Foreachloop(char[] a, char x)//foreach loop
{
foreach(char s in a)
{
if(s==x) return true;
}
return false;
}
}
}
请帮助我理解我无法理解。我的编码老师告诉我们,hashset 的性能应该更快。
但在我上面的测试代码中证明它没有
或者我的做法有什么问题?
【问题讨论】:
-
将
HashSet<char> hashSearch = new HashSet<char>(a);放在测试之外。查找Hash比查找数组要快,但是创建Hash需要额外的时间。 -
另外,当测量这种快速操作的性能时,迭代多次并计算平均时间,比如重复操作一百万次并测量那一百万次的时间,然后除以所用的时间.由于计时器分辨率和系统活动的干扰,测量如此短的时间间隔非常不准确。
-
是的,我明白了,谢谢...