Skip to content

Commit 547ab9e

Browse files
authored
Deoptimize the exceptional cases in favor of optimal path (#62997)
1 parent 21c7181 commit 547ab9e

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
@@ -115,12 +115,10 @@ public RestoringComponentStateSubscription RegisterOnRestoring(Action callback,
115115
throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback.");
116116
}
117117

118-
if (_currentState.ContainsKey(key))
118+
if (!_currentState.TryAdd(key, JsonSerializer.SerializeToUtf8Bytes(instance, JsonSerializerOptionsProvider.Options)))
119119
{
120120
throw new ArgumentException($"There is already a persisted object under the same key '{key}'");
121121
}
122-
123-
_currentState.Add(key, JsonSerializer.SerializeToUtf8Bytes(instance, JsonSerializerOptionsProvider.Options));
124122
}
125123

126124
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
@@ -133,12 +131,10 @@ internal void PersistAsJson(string key, object instance, [DynamicallyAccessedMem
133131
throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback.");
134132
}
135133

136-
if (_currentState.ContainsKey(key))
134+
if (!_currentState.TryAdd(key, JsonSerializer.SerializeToUtf8Bytes(instance, type, JsonSerializerOptionsProvider.Options)))
137135
{
138136
throw new ArgumentException($"There is already a persisted object under the same key '{key}'");
139137
}
140-
141-
_currentState.Add(key, JsonSerializer.SerializeToUtf8Bytes(instance, type, JsonSerializerOptionsProvider.Options));
142138
}
143139

144140
/// <summary>
@@ -155,12 +151,10 @@ internal void PersistAsBytes(string key, byte[] data)
155151
throw new InvalidOperationException("Persisting state is only allowed during an OnPersisting callback.");
156152
}
157153

158-
if (_currentState.ContainsKey(key))
154+
if (!_currentState.TryAdd(key, data))
159155
{
160156
throw new ArgumentException($"There is already a persisted object under the same key '{key}'");
161157
}
162-
163-
_currentState.Add(key, data);
164158
}
165159

166160
/// <summary>

0 commit comments

Comments
 (0)