Skip to content

Commit 1735b2f

Browse files
committed
Deoptimize the exceptional cases in favor of optimal path
1 parent a400348 commit 1735b2f

File tree

1 file changed

+3
-9
lines changed

1 file changed

+3
-9
lines changed

src/Components/Components/src/PersistentComponentState.cs

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,10 @@ public PersistingComponentStateSubscription RegisterOnPersisting(Func<Task> call
8484
throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback.");
8585
}
8686

87-
if (_currentState.ContainsKey(key))
87+
if (!_currentState.TryAdd(key, JsonSerializer.SerializeToUtf8Bytes(instance, JsonSerializerOptionsProvider.Options)))
8888
{
8989
throw new ArgumentException($"There is already a persisted object under the same key '{key}'");
9090
}
91-
92-
_currentState.Add(key, JsonSerializer.SerializeToUtf8Bytes(instance, JsonSerializerOptionsProvider.Options));
9391
}
9492

9593
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
@@ -102,12 +100,10 @@ internal void PersistAsJson(string key, object instance, [DynamicallyAccessedMem
102100
throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback.");
103101
}
104102

105-
if (_currentState.ContainsKey(key))
103+
if (!_currentState.TryAdd(key, JsonSerializer.SerializeToUtf8Bytes(instance, type, JsonSerializerOptionsProvider.Options)))
106104
{
107105
throw new ArgumentException($"There is already a persisted object under the same key '{key}'");
108106
}
109-
110-
_currentState.Add(key, JsonSerializer.SerializeToUtf8Bytes(instance, type, JsonSerializerOptionsProvider.Options));
111107
}
112108

113109
/// <summary>
@@ -124,12 +120,10 @@ internal void PersistAsBytes(string key, byte[] data)
124120
throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback.");
125121
}
126122

127-
if (_currentState.ContainsKey(key))
123+
if (!_currentState.TryAdd(key, data))
128124
{
129125
throw new ArgumentException($"There is already a persisted object under the same key '{key}'");
130126
}
131-
132-
_currentState.Add(key, data);
133127
}
134128

135129
/// <summary>

0 commit comments

Comments
 (0)