Skip to content

Instantly share code, notes, and snippets.

@salluvada
Created June 4, 2020 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salluvada/be22c3858914f674d2fb5d155824fdb8 to your computer and use it in GitHub Desktop.
Save salluvada/be22c3858914f674d2fb5d155824fdb8 to your computer and use it in GitHub Desktop.
compare linq and dict on performance for finding duplicates in a string array.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
namespace rnd
{
class Program
{
static void Main(string[] args)
{
string sentence = "This is a test for duplicate arrays to test performance of different solution approaches some words in this sentence are duplicate while the others are not duplicate. The test is to see whether the linq based approach takes more time or whether the dictionary based approach takes more time to process over a million iterations";
var array = sentence.Split(" ");
var linqwatch = new Stopwatch();
var dictwatch = new Stopwatch();
linqwatch.Start();
for (int i = 0; i < 1000000; i++)
{
PrintDuplicatesLinq(array);
}
linqwatch.Stop();
dictwatch.Start();
for (int i = 0; i < 1000000; i++)
{
PrintDuplicatesDict(array);
}
dictwatch.Stop();
Console.WriteLine($"Linq time: {linqwatch.ElapsedMilliseconds}, Dict time: {dictwatch.ElapsedMilliseconds}");
}
public static void PrintDuplicatesLinq(string[] stringArray){
var duplicates = stringArray.ToList().GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
duplicates.ForEach(x=>{Console.WriteLine(x);});
}
public static void PrintDuplicatesDict(string[] stringArray){
Dictionary<string, int> wordslist = new Dictionary<string, int>();
foreach (var item in stringArray)
{
if (wordslist.ContainsKey(item)){
Console.WriteLine(item);
}else{
wordslist[item] = 1;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment