[.NET]產生不重覆的數值(List vs HashSet)

  • 10337
  • 0
  • .NET
  • 2013-05-31

在產生不重覆的數值時,可考慮使用HashSet,效能會比使用List來的好哦!

在網路上看到「Generate distinct random numbers in C#」,要產生不重覆的數值,可透過HashSet<int>來產生,會比List<int>來的快哦!

所以在這裡記錄一下。

環境: Win8 X64, Intel i7, 8G RAM, VS2012

如下,在0~50000之間取30000個不重覆的數值,

以下使用List<int>,花費時間為 3.3094352


Random rand = new Random();
List<int> result = new List<int>();
const int minValue = 0;
const int maxValue = 50001;
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing
stopwatch.Start();
for (Int32 i = 0; i < 30000; i++)
{
	int curValue = rand.Next(minValue, maxValue);
	while (result.Contains(curValue))
	{
		curValue = rand.Next(minValue, maxValue);
	}
	result.Add(curValue);
}
var resultArray = result.ToArray();
// Stop timing
stopwatch.Stop();

// Write result
Console.WriteLine("Time elapsed: {0}",
	stopwatch.Elapsed);

 

以下使用HashSet<int>,花費時間為 0.0155939


Random rand = new Random();
HashSet<int> check = new HashSet<int>();
const int minValue = 0;
const int maxValue = 50001;
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing
stopwatch.Start();
for (Int32 i = 0; i < 30000; i++)
{
	int curValue = rand.Next(minValue, maxValue);
	while (check.Contains(curValue))
	{
		curValue = rand.Next(minValue, maxValue);
	}
	check.Add(curValue);
}
var resultArray = check.ToArray();
// Stop timing
stopwatch.Stop();

// Write result
Console.WriteLine("Time elapsed: {0}",
	stopwatch.Elapsed);

 

感謝「Aaron」的提醒微笑

參考資料:Generate distinct random numbers in C#

感謝「KKBruce」的提醒,因為使用While來檢查是否存在,對整體的測試或許有些不公平,以上測試僅供參考。

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^