Skip to content

Commit a02e3ce

Browse files
committed
Remove linq from KeyValue this[item]
This avoids allocating every time
1 parent a774770 commit a02e3ce

2 files changed

Lines changed: 29 additions & 14 deletions

File tree

SteamKit2/SteamKit2/Types/KeyValue.cs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
using System.Diagnostics.CodeAnalysis;
99
using System.Globalization;
1010
using System.IO;
11-
using System.Linq;
1211
using System.Text;
1312

1413
namespace SteamKit2
@@ -278,27 +277,28 @@ public KeyValue this[ string key ]
278277
{
279278
ArgumentNullException.ThrowIfNull( key );
280279

281-
var child = this.Children
282-
.FirstOrDefault( c => string.Equals( c.Name, key, StringComparison.OrdinalIgnoreCase ) );
283-
284-
if ( child == null )
280+
foreach ( var c in this.Children )
285281
{
286-
return Invalid;
282+
if ( string.Equals( c.Name, key, StringComparison.OrdinalIgnoreCase ) )
283+
{
284+
return c;
285+
}
287286
}
288287

289-
return child;
288+
return Invalid;
290289
}
291290
set
292291
{
293292
ArgumentNullException.ThrowIfNull( key );
294293

295-
var existingChild = this.Children
296-
.FirstOrDefault( c => string.Equals( c.Name, key, StringComparison.OrdinalIgnoreCase ) );
297-
298-
if ( existingChild != null )
294+
foreach ( var c in this.Children )
299295
{
300-
// if the key already exists, remove the old one
301-
this.Children.Remove( existingChild );
296+
if ( string.Equals( c.Name, key, StringComparison.OrdinalIgnoreCase ) )
297+
{
298+
// if the key already exists, remove the old one
299+
this.Children.Remove( c );
300+
break;
301+
}
302302
}
303303

304304
// ensure the given KV actually has the correct key assigned
@@ -810,7 +810,7 @@ static bool TryReadAsBinaryCore( Stream input, KeyValue current, KeyValue? paren
810810
}
811811

812812
current.Name = input.ReadNullTermString( Encoding.UTF8 );
813-
813+
814814
switch ( type )
815815
{
816816
case Type.None:

SteamKit2/Tests/KeyValueFacts.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,21 @@ public void KeyValueIndexerUpdatesKey()
6363
Assert.Equal( "subkey", kv["subkey"].Name );
6464
}
6565

66+
[Fact]
67+
public void KeyValueIndexerHandlesCaseInsensitiveDuplicates()
68+
{
69+
KeyValue kv = new KeyValue();
70+
71+
kv["key"] = new KeyValue();
72+
Assert.Single( kv.Children );
73+
74+
kv["KEY"] = new KeyValue(); // Different case
75+
Assert.Single( kv.Children ); // Should still be 1, not 2
76+
77+
kv["Key"] = new KeyValue(); // Another variation
78+
Assert.Single( kv.Children ); // Should still be 1
79+
}
80+
6681
[Fact]
6782
public void KeyValueLoadsFromString()
6883
{

0 commit comments

Comments
 (0)