Created
April 4, 2023 12:34
-
-
Save Webreaper/b69419e788e14cdd3ca01bfaf894e3e8 to your computer and use it in GitHub Desktop.
Performance discussion from https://www.reddit.com/r/csharp/comments/12bgm2x/why_is_listexists_slower_in_c_than_find_in_js/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
using System.Security.Cryptography; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace CsTest; | |
[SimpleJob] | |
public class MainClass | |
{ | |
public static void Main( string[] args ) | |
{ | |
// var summary = BenchmarkRunner.Run<MainClass>(); | |
var cMainClass = new MainClass(); | |
var setupWatch = Stopwatch.StartNew(); | |
cMainClass.Setup(); | |
Console.WriteLine( $"Setup: {setupWatch.ElapsedMilliseconds}ms" ); | |
var watch = Stopwatch.StartNew(); | |
cMainClass.Test(); | |
watch.Stop(); | |
Console.WriteLine( $"Test: {watch.ElapsedMilliseconds}ms" ); | |
Console.WriteLine( $"Items Found: {cMainClass._list.Count}" ); | |
var watch2 = Stopwatch.StartNew(); | |
cMainClass.Test2(); | |
watch2.Stop(); | |
Console.WriteLine( $"Test with dict: {watch2.ElapsedMilliseconds}ms" ); | |
Console.WriteLine( $"Items Found: {cMainClass._list.Count}" ); | |
} | |
private readonly List<Obj> _list = new(); | |
private readonly Dictionary<int, Obj> _dict = new(); | |
private readonly List<int> _testList = new(); | |
[GlobalSetup] | |
public void Setup() | |
{ | |
for( var i = 0; i < 10000; i++ ) | |
_list.Add( new Obj | |
{ | |
Id = RandomNumberGenerator.GetInt32( 1, 10000 ), | |
Name = "Name", | |
Description = "Description", | |
} ); | |
_testList.AddRange( Enumerable.Range( 0, 1000000 ).Select( x => RandomNumberGenerator.GetInt32( 1, 10000 ) )); | |
} | |
[Benchmark] | |
public void Test() | |
{ | |
foreach( var id in _testList ) | |
{ | |
if( _list.Exists( obj => obj.Id == id ) ) | |
continue; | |
_list.Add( new Obj | |
{ | |
Id = id, | |
Name = "Name", | |
Description = "Description", | |
} ); | |
} | |
} | |
public void Test2() | |
{ | |
foreach( var id in _testList ) | |
{ | |
if( _dict.ContainsKey( id ) ) | |
continue; | |
_dict[id] = new Obj | |
{ | |
Id = id, | |
Name = "Name", | |
Description = "Description", | |
}; | |
} | |
} | |
} | |
public class Obj | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } = null!; | |
public string Description { get; set; } = null!; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment