【问题标题】:C# why is hashset slow in my test. Please help me understandC# 为什么 hashset 在我的测试中很慢。请帮我理解
【发布时间】: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&lt;char&gt; hashSearch = new HashSet&lt;char&gt;(a); 放在测试之外。查找Hash比查找数组要快,但是创建Hash需要额外的时间。
  • 另外,当测量这种快速操作的性能时,迭代多次并计算平均时间,比如重复操作一百万次并测量那一百万次的时间,然后除以所用的时间.由于计时器分辨率和系统活动的干扰,测量如此短的时间间隔非常不准确。
  • 是的,我明白了,谢谢...

标签: c# hashset


【解决方案1】:

您正在测量创建 HashSet 并在其中进行搜索的时间。尝试仅测量查找时间。

此外,您正在搜索范围的第一个元素“a”,线性搜索将在仅测试第一个元素后成功并返回成功。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多