Skip to content

Commit f7bc2d9

Browse files
committed
avoid .Any() on hot paths
This allocates an enumerator unnecessarily if we already have the count available.
1 parent b446278 commit f7bc2d9

16 files changed

Lines changed: 30 additions & 30 deletions

src/SMAPI/Framework/ContentCoordinator.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ public T LoadManagedAsset<T>(string contentManagerId, IAssetName relativePath)
366366
/// <param name="predicate">Matches the asset keys to invalidate.</param>
367367
/// <param name="dispose">Whether to dispose invalidated assets. This should only be <c>true</c> when they're being invalidated as part of a dispose, to avoid crashing the game.</param>
368368
/// <returns>Returns the invalidated asset keys.</returns>
369-
public IEnumerable<IAssetName> InvalidateCache(Func<IAssetInfo, bool> predicate, bool dispose = false)
369+
public ICollection<IAssetName> InvalidateCache(Func<IAssetInfo, bool> predicate, bool dispose = false)
370370
{
371371
string locale = this.GetLocale();
372372
return this.InvalidateCache((_, rawName, type) =>
@@ -381,7 +381,7 @@ public IEnumerable<IAssetName> InvalidateCache(Func<IAssetInfo, bool> predicate,
381381
/// <param name="predicate">Matches the asset keys to invalidate.</param>
382382
/// <param name="dispose">Whether to dispose invalidated assets. This should only be <c>true</c> when they're being invalidated as part of a dispose, to avoid crashing the game.</param>
383383
/// <returns>Returns the invalidated asset names.</returns>
384-
public IEnumerable<IAssetName> InvalidateCache(Func<IContentManager, string, Type, bool> predicate, bool dispose = false)
384+
public ICollection<IAssetName> InvalidateCache(Func<IContentManager, string, Type, bool> predicate, bool dispose = false)
385385
{
386386
// invalidate cache & track removed assets
387387
IDictionary<IAssetName, Type> invalidatedAssets = new Dictionary<IAssetName, Type>();
@@ -438,7 +438,7 @@ public IEnumerable<IAssetName> InvalidateCache(Func<IContentManager, string, Typ
438438
});
439439

440440
// handle invalidation
441-
if (invalidatedAssets.Any())
441+
if (invalidatedAssets.Count > 0)
442442
{
443443
// clear cached editor checks
444444
foreach (IAssetName name in invalidatedAssets.Keys)

src/SMAPI/Framework/Deprecations/DeprecationManager.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ public void PlaceholderWarn(string version, DeprecationLevel severity) { }
9494
/// <summary>Print any queued messages.</summary>
9595
public void PrintQueued()
9696
{
97-
if (!this.QueuedWarnings.Any())
97+
if (this.QueuedWarnings.Count == 0)
9898
return;
9999

100100
foreach (DeprecationWarning warning in this.QueuedWarnings.OrderBy(p => p.ModName).ThenBy(p => p.NounPhrase))
@@ -149,7 +149,7 @@ public void PrintQueued()
149149
/// <param name="unlessStackIncludes">A list of stack trace substrings which should suppress deprecation warnings if they appear in the stack trace.</param>
150150
private bool ShouldSuppress(ImmutableStackTrace stack, string[]? unlessStackIncludes)
151151
{
152-
if (unlessStackIncludes?.Any() == true)
152+
if (unlessStackIncludes is { Length: > 0 })
153153
{
154154
string stackTrace = stack.ToString();
155155
foreach (string method in unlessStackIncludes)

src/SMAPI/Framework/Input/SInputState.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -271,11 +271,11 @@ private bool ApplyOverrides(ISet<SButton> pressed, ISet<SButton> released, GameP
271271
}
272272

273273
// override states
274-
if (keyboardOverrides.Any())
274+
if (keyboardOverrides.Count > 0)
275275
keyboard.OverrideButtons(keyboardOverrides);
276-
if (controllerOverrides.Any())
276+
if (controllerOverrides.Count > 0)
277277
controller.OverrideButtons(controllerOverrides);
278-
if (mouseOverrides.Any())
278+
if (mouseOverrides.Count > 0)
279279
mouse.OverrideButtons(mouseOverrides);
280280

281281
return true;

src/SMAPI/Framework/ModHelpers/GameContentHelper.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,22 +107,22 @@ public bool InvalidateCache(string key)
107107
public bool InvalidateCache(IAssetName assetName)
108108
{
109109
this.Monitor.Log($"Requested cache invalidation for '{assetName}'.");
110-
return this.ContentCore.InvalidateCache(asset => asset.Name.IsEquivalentTo(assetName)).Any();
110+
return this.ContentCore.InvalidateCache(asset => asset.Name.IsEquivalentTo(assetName)).Count > 0;
111111
}
112112

113113
/// <inheritdoc />
114114
public bool InvalidateCache<T>()
115115
where T : notnull
116116
{
117117
this.Monitor.Log($"Requested cache invalidation for all assets of type {typeof(T)}. This is an expensive operation and should be avoided if possible.");
118-
return this.ContentCore.InvalidateCache((_, _, type) => typeof(T).IsAssignableFrom(type)).Any();
118+
return this.ContentCore.InvalidateCache((_, _, type) => typeof(T).IsAssignableFrom(type)).Count > 0;
119119
}
120120

121121
/// <inheritdoc />
122122
public bool InvalidateCache(Func<IAssetInfo, bool> predicate)
123123
{
124124
this.Monitor.Log("Requested cache invalidation for all assets matching a predicate.");
125-
return this.ContentCore.InvalidateCache(predicate).Any();
125+
return this.ContentCore.InvalidateCache(predicate).Count > 0;
126126
}
127127

128128
/// <inheritdoc />

src/SMAPI/Framework/ModLoading/AssemblyLoader.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ select name
123123
}
124124

125125
// validate load
126-
if (!assemblies.Any() || assemblies[0].Status == AssemblyLoadStatus.Failed)
126+
if (assemblies.Length == 0 || assemblies[0].Status == AssemblyLoadStatus.Failed)
127127
{
128128
throw new SAssemblyLoadFailedException(!assemblyFile.Exists
129129
? $"Could not load '{assemblyFile.FullName}' because it doesn't exist."
@@ -475,7 +475,7 @@ private void ProcessInstructionHandleResult(IModMetadata mod, IInstructionHandle
475475

476476
// format messages
477477
string phrase;
478-
if (!handler.Phrases.Any())
478+
if (handler.Phrases.Count == 0)
479479
phrase = handler.DefaultPhrase;
480480
else if (this.LogTechnicalDetailsForBrokenMods && result == InstructionHandleResult.NotCompatible)
481481
phrase = "\n - " + string.Join(";\n - ", handler.Phrases.OrderBy(p => p, StringComparer.OrdinalIgnoreCase));

src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public EventFinder(string fullTypeName, string eventName, InstructionHandleResul
5353
/// <inheritdoc />
5454
public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction)
5555
{
56-
if (this.MethodNames.Any())
56+
if (this.MethodNames.Count > 0)
5757
{
5858
MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction);
5959
if (methodRef != null && methodRef.DeclaringType.FullName == this.FullTypeName && this.MethodNames.Contains(methodRef.Name))

src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public FieldFinder(string fullTypeName, string fieldName, InstructionHandleResul
4747
/// <inheritdoc />
4848
public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction)
4949
{
50-
if (this.FieldNames.Any())
50+
if (this.FieldNames.Count > 0)
5151
{
5252
FieldReference? fieldRef = RewriteHelper.AsFieldReference(instruction);
5353
if (fieldRef != null && fieldRef.DeclaringType.FullName == this.FullTypeName && this.FieldNames.Contains(fieldRef.Name))

src/SMAPI/Framework/ModLoading/Finders/ReferenceToInvalidMemberFinder.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public override bool Handle(ModuleDefinition module, ILProcessor cil, Instructio
6464
if (methodDef != null && this.ShouldValidate(methodRef.DeclaringType))
6565
{
6666
MethodDefinition[]? candidateMethods = methodRef.DeclaringType.Resolve()?.Methods.Where(found => found.Name == methodRef.Name).ToArray();
67-
if (candidateMethods?.Any() is true && candidateMethods.All(method => !RewriteHelper.LooksLikeSameType(method.ReturnType, methodDef.ReturnType)))
67+
if (candidateMethods is { Length: > 0 } && candidateMethods.All(method => !RewriteHelper.LooksLikeSameType(method.ReturnType, methodDef.ReturnType)))
6868
this.MarkFlag(InstructionHandleResult.NotCompatible, $"reference to {this.GetMemberDisplayName(methodDef)} (no such method returns {this.GetFriendlyTypeName(methodDef.ReturnType)})");
6969
}
7070

src/SMAPI/Framework/ModLoading/ModResolver.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ public void ValidateManifests(IEnumerable<IModMetadata> mods, ISemanticVersion a
192192
/// <param name="modIdsToLoadLate">The mod IDs SMAPI should load after any other mods.</param>
193193
public IModMetadata[] ApplyLoadOrderOverrides(IModMetadata[] mods, HashSet<string> modIdsToLoadEarly, HashSet<string> modIdsToLoadLate)
194194
{
195-
if (!modIdsToLoadEarly.Any() && !modIdsToLoadLate.Any())
195+
if (modIdsToLoadEarly.Count == 0 && modIdsToLoadLate.Count == 0)
196196
return mods;
197197

198198
string[] earlyArray = modIdsToLoadEarly.ToArray();
@@ -283,7 +283,7 @@ private ModDependencyStatus ProcessDependencies(IReadOnlyList<IModMetadata> mods
283283
ModDependency[] dependencies = this.GetDependenciesFrom(mod.Manifest, mods).ToArray();
284284

285285
// mark sorted if no dependencies
286-
if (!dependencies.Any())
286+
if (dependencies.Length == 0)
287287
{
288288
sortedMods.Push(mod);
289289
return states[mod] = ModDependencyStatus.Sorted;
@@ -306,7 +306,7 @@ orderby displayName
306306
? $"{displayName}: {modUrl}"
307307
: displayName
308308
).ToArray();
309-
if (failedModNames.Any())
309+
if (failedModNames.Length > 0)
310310
{
311311
sortedMods.Push(mod);
312312
mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.MissingDependencies, $"it requires mods which aren't installed ({string.Join(", ", failedModNames)}).");
@@ -325,7 +325,7 @@ from entry in dependencies
325325
select $"{entry.Mod!.DisplayName} (needs {entry.MinVersion} or later)"
326326
)
327327
.ToArray();
328-
if (failedLabels.Any())
328+
if (failedLabels.Length > 0)
329329
{
330330
sortedMods.Push(mod);
331331
mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.MissingDependencies, $"it needs newer versions of some mods: {string.Join(", ", failedLabels)}.");
@@ -430,7 +430,7 @@ private IEnumerable<ModDependency> GetDependenciesFrom(IManifest manifest, IRead
430430
$"marked {statusLabel} in SMAPI's internal compatibility list for "
431431
+ (data.StatusUpperVersion != null ? $"versions up to {data.StatusUpperVersion}" : "all versions")
432432
+ ": "
433-
+ (reasons.Any() ? string.Join(": ", reasons) : "no reason given")
433+
+ (reasons.Length > 0 ? string.Join(": ", reasons) : "no reason given")
434434
+ ".";
435435
}
436436

src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ private IEnumerable<string> GetTypeSymbols(string typeName)
112112

113113
Queue<char> queue = new(typeName);
114114
string symbol = "";
115-
while (queue.Any())
115+
while (queue.Count > 0)
116116
{
117117
char ch = queue.Dequeue();
118118
switch (ch)

0 commit comments

Comments
 (0)