diff --git a/samples/BenchmarkDotNet.Samples/IntroFilters.cs b/samples/BenchmarkDotNet.Samples/IntroFilters.cs index 2d030b1f75..8ade3662fc 100644 --- a/samples/BenchmarkDotNet.Samples/IntroFilters.cs +++ b/samples/BenchmarkDotNet.Samples/IntroFilters.cs @@ -16,8 +16,8 @@ public Config() { // benchmark with names which contains "A" OR "1" AddFilter(new DisjunctionFilter( - new NameFilter(name => name.Contains("A")), - new NameFilter(name => name.Contains("1")) + new NameFilter(name => name.Contains('A')), + new NameFilter(name => name.Contains('1')) )); // benchmark with names with length < 3 diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/ConcurrencyVisualizerProfiler.cs b/src/BenchmarkDotNet.Diagnostics.Windows/ConcurrencyVisualizerProfiler.cs index 8fbe1d5417..956dec009b 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/ConcurrencyVisualizerProfiler.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/ConcurrencyVisualizerProfiler.cs @@ -48,7 +48,7 @@ public class ConcurrencyVisualizerProfiler : IProfiler public void DisplayResults(ILogger logger) { - if (!benchmarkToCvTraceFile.Any()) + if (benchmarkToCvTraceFile.Count == 0) return; logger.WriteLineInfo($"Exported {benchmarkToCvTraceFile.Count} CV trace file(s). Example:"); diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/EtwProfiler.cs b/src/BenchmarkDotNet.Diagnostics.Windows/EtwProfiler.cs index 7d641b2357..2ae8d4118c 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/EtwProfiler.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/EtwProfiler.cs @@ -81,7 +81,7 @@ public IEnumerable ProcessResults(DiagnoserResults results) public void DisplayResults(ILogger logger) { - if (!benchmarkToEtlFile.Any()) + if (benchmarkToEtlFile.Count == 0) return; logger.WriteLineInfo($"Exported {benchmarkToEtlFile.Count} trace file(s). Example:"); @@ -95,7 +95,7 @@ private void Start(DiagnoserActionParameters parameters) .Select(counter => HardwareCounters.FromCounter(counter, config.IntervalSelectors.TryGetValue(counter, out var selector) ? selector : GetInterval)) .ToArray(); - if (counters.Any()) // we need to enable the counters before starting the kernel session + if (counters.Length != 0) // we need to enable the counters before starting the kernel session HardwareCounters.Enable(counters); try diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/TraceLogParser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/TraceLogParser.cs index e0d42c2ffb..64327ca3c0 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/TraceLogParser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/TraceLogParser.cs @@ -81,10 +81,10 @@ private void OnPmcIntervalChange(SampledProfileIntervalTraceData data) private void OnPmcEvent(PMCCounterProfTraceData data) { // if given process did not emit Benchmarking events before, we don't care about it - if (!processIdToData.ContainsKey(data.ProcessID)) + if (!processIdToData.TryGetValue(data.ProcessID, out ProcessMetrics? value)) return; - processIdToData[data.ProcessID].HandleNewSample(data.TimeStampRelativeMSec, data.InstructionPointer, data.ProfileSource); + value.HandleNewSample(data.TimeStampRelativeMSec, data.InstructionPointer, data.ProfileSource); } } @@ -96,7 +96,7 @@ public class ProcessMetrics private readonly List<(double timeStamp, ulong instructionPointer, int profileSource)> samples = []; - public bool HasBenchmarkEvents => overheadTimestamps.Any() || workloadTimestamps.Any(); + public bool HasBenchmarkEvents => overheadTimestamps.Count != 0 || workloadTimestamps.Count != 0; public void HandleIterationEvent(double timeStamp, IterationMode iterationMode, long totalOperations) { diff --git a/src/BenchmarkDotNet/Analysers/ConclusionHelper.cs b/src/BenchmarkDotNet/Analysers/ConclusionHelper.cs index a04d623461..bd4b8f7b34 100644 --- a/src/BenchmarkDotNet/Analysers/ConclusionHelper.cs +++ b/src/BenchmarkDotNet/Analysers/ConclusionHelper.cs @@ -14,7 +14,7 @@ public static void Print(ILogger logger, IEnumerable conclusions) private static void PrintFiltered(IEnumerable conclusions, ConclusionKind kind, string title, Action printLine) { var filtered = conclusions.Where(c => c.Kind == kind).ToArray(); - if (filtered.Any()) + if (filtered.Length != 0) { printLine(""); printLine($"// * {title} *"); diff --git a/src/BenchmarkDotNet/Analysers/EnvironmentAnalyser.cs b/src/BenchmarkDotNet/Analysers/EnvironmentAnalyser.cs index 419e531d3d..cb85bee01c 100644 --- a/src/BenchmarkDotNet/Analysers/EnvironmentAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/EnvironmentAnalyser.cs @@ -32,7 +32,7 @@ protected override IEnumerable AnalyseSummary(Summary summary) if (unexpectedExit) { var avProducts = summary.HostEnvironmentInfo.AntivirusProducts.Value; - if (avProducts.Any()) + if (avProducts.Count != 0) yield return CreateWarning(CreateWarningAboutAntivirus(avProducts)); } diff --git a/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs b/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs index d9e4ec3ce3..c746c99f5f 100644 --- a/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs @@ -27,7 +27,7 @@ protected override IEnumerable AnalyseReport(BenchmarkReport report, var actualOutliers = statistics.GetActualOutliers(outlierMode); var cultureInfo = summary.GetCultureInfo(); - if (allOutliers.Any()) + if (allOutliers.Length != 0) yield return CreateHint(GetMessage(actualOutliers, allOutliers, statistics.LowerOutliers, statistics.UpperOutliers, cultureInfo), report); } @@ -54,7 +54,7 @@ string Format(int n, string verb) var rangeMessages = new List { GetRangeMessage(lowerOutliers), GetRangeMessage(upperOutliers) }; rangeMessages.RemoveAll(string.IsNullOrEmpty); - string rangeMessage = rangeMessages.Any() + string rangeMessage = rangeMessages.Count != 0 ? " (" + string.Join(", ", rangeMessages) + ")" : string.Empty; diff --git a/src/BenchmarkDotNet/Analysers/ZeroMeasurementAnalyser.cs b/src/BenchmarkDotNet/Analysers/ZeroMeasurementAnalyser.cs index 9b31294330..93ca8cdcc9 100644 --- a/src/BenchmarkDotNet/Analysers/ZeroMeasurementAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/ZeroMeasurementAnalyser.cs @@ -30,7 +30,7 @@ protected override IEnumerable AnalyseReport(BenchmarkReport report, var workloadSample = workloadMeasurements.GetStatistics().Sample; var threshold = currentFrequency.Value.ToResolution().Nanoseconds / 2; - var zeroMeasurement = overheadMeasurements.Any() + var zeroMeasurement = overheadMeasurements.Length != 0 ? ZeroMeasurementHelper.AreIndistinguishable(workloadSample, overheadMeasurements.GetStatistics().Sample) : ZeroMeasurementHelper.IsNegligible(workloadSample, threshold); diff --git a/src/BenchmarkDotNet/Code/CodeGenerator.cs b/src/BenchmarkDotNet/Code/CodeGenerator.cs index c575d01713..0c76c0692d 100644 --- a/src/BenchmarkDotNet/Code/CodeGenerator.cs +++ b/src/BenchmarkDotNet/Code/CodeGenerator.cs @@ -69,7 +69,7 @@ private static (bool, string) GetShadowCopySettings() { string benchmarkDotNetLocation = Path.GetDirectoryName(typeof(CodeGenerator).GetTypeInfo().Assembly.Location)!; - if (benchmarkDotNetLocation != null && benchmarkDotNetLocation.IndexOf("LINQPAD", StringComparison.OrdinalIgnoreCase) >= 0) + if (benchmarkDotNetLocation != null && benchmarkDotNetLocation.Contains("LINQPAD", StringComparison.OrdinalIgnoreCase)) { /* "LINQPad normally puts the compiled query into a different folder than the referenced assemblies * - this allows for optimizations to reduce file I/O, which is important in the scratchpad scenario" @@ -239,7 +239,7 @@ private static string GetEngineFactoryTypeName(BenchmarkCase benchmarkCase) var factory = benchmarkCase.Job.ResolveValue(InfrastructureMode.EngineFactoryCharacteristic, InfrastructureResolver.Instance)!; var factoryType = factory.GetType(); - if (!factoryType.GetTypeInfo().DeclaredConstructors.Any(ctor => ctor.IsPublic && !ctor.GetParameters().Any())) + if (!factoryType.GetTypeInfo().DeclaredConstructors.Any(ctor => ctor.IsPublic && ctor.GetParameters().Length == 0)) { throw new NotSupportedException("Custom factory must have a public parameterless constructor"); } diff --git a/src/BenchmarkDotNet/Configs/ImmutableConfig.cs b/src/BenchmarkDotNet/Configs/ImmutableConfig.cs index 5b6f56ef77..d53ed8091d 100644 --- a/src/BenchmarkDotNet/Configs/ImmutableConfig.cs +++ b/src/BenchmarkDotNet/Configs/ImmutableConfig.cs @@ -122,7 +122,7 @@ internal ImmutableConfig( { var diagnosersForGivenMode = diagnosers.Where(diagnoser => runModeComparer(diagnoser.GetRunMode(benchmarkCase))).ToImmutableHashSet(); - return diagnosersForGivenMode.Any() ? new CompositeDiagnoser(diagnosersForGivenMode) : null; + return !diagnosersForGivenMode.IsEmpty ? new CompositeDiagnoser(diagnosersForGivenMode) : null; } public IReadOnlyList ConfigAnalysisConclusion { get; private set; } diff --git a/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs b/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs index 18c1b65fd6..6985a66be0 100644 --- a/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs +++ b/src/BenchmarkDotNet/Configs/ImmutableConfigBuilder.cs @@ -88,8 +88,7 @@ private static ImmutableHashSet GetDiagnosers(IEnumerable()); foreach (var diagnoser in diagnosers) - if (!builder.Contains(diagnoser)) - builder.Add(diagnoser); + builder.Add(diagnoser); if (!uniqueHardwareCounters.IsEmpty && !diagnosers.OfType().Any()) { @@ -187,13 +186,11 @@ private static ImmutableHashSet GetAnalysers(IEnumerable a var builder = ImmutableHashSet.CreateBuilder(); foreach (var analyser in analysers) - if (!builder.Contains(analyser)) - builder.Add(analyser); + builder.Add(analyser); foreach (var diagnoser in uniqueDiagnosers) foreach (var analyser in diagnoser.Analysers) - if (!builder.Contains(analyser)) - builder.Add(analyser); + builder.Add(analyser); return builder.ToImmutable(); } @@ -232,7 +229,7 @@ private static IReadOnlyList GetRunnableJobs(IEnumerable jobs) var customDefaultJob = unique.SingleOrDefault(job => job.Meta.IsDefault); var defaultJob = customDefaultJob ?? Job.Default; - if (!result.Any()) + if (result.Count == 0) result.Add(defaultJob); foreach (var mutatorJob in unique.Where(job => job.Meta.IsMutator)) diff --git a/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs b/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs index 3c15744439..33e5ee8faf 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs @@ -287,7 +287,7 @@ private static bool Validate(CommandLineOptions options, ILogger logger) { if (!TryParse(runtime, out RuntimeMoniker runtimeMoniker)) { - logger.WriteLineError($"The provided runtime \"{runtime}\" is invalid. Available options are: {string.Join(", ", Enum.GetNames(typeof(RuntimeMoniker)).Select(name => name.ToLower()))}."); + logger.WriteLineError($"The provided runtime \"{runtime}\" is invalid. Available options are: {string.Join(", ", Enum.GetNames().Select(name => name.ToLower()))}."); return false; } else if (runtimeMoniker == RuntimeMoniker.MonoAOTLLVM && (options.AOTCompilerPath == null || options.AOTCompilerPath.IsNotNullButDoesNotExist())) @@ -353,7 +353,7 @@ private static bool Validate(CommandLineOptions options, ILogger logger) foreach (var counterName in options.HardwareCounters) if (!Enum.TryParse(counterName, ignoreCase: true, out HardwareCounter _)) { - logger.WriteLineError($"The provided hardware counter \"{counterName}\" is invalid. Available options are: {string.Join("+", Enum.GetNames(typeof(HardwareCounter)))}."); + logger.WriteLineError($"The provided hardware counter \"{counterName}\" is invalid. Available options are: {string.Join("+", Enum.GetNames())}."); return false; } diff --git a/src/BenchmarkDotNet/Diagnosers/EventPipeProfiler.cs b/src/BenchmarkDotNet/Diagnosers/EventPipeProfiler.cs index 7d4b726233..f96eb77ca9 100644 --- a/src/BenchmarkDotNet/Diagnosers/EventPipeProfiler.cs +++ b/src/BenchmarkDotNet/Diagnosers/EventPipeProfiler.cs @@ -119,7 +119,7 @@ public IEnumerable ProcessResults(DiagnoserResults results) public void DisplayResults(ILogger resultLogger) { - if (!benchmarkToTraceFile.Any()) + if (benchmarkToTraceFile.Count == 0) return; resultLogger.WriteLineInfo($"Exported {benchmarkToTraceFile.Count} trace file(s). Example:"); diff --git a/src/BenchmarkDotNet/Diagnosers/PerfCollectProfiler.cs b/src/BenchmarkDotNet/Diagnosers/PerfCollectProfiler.cs index e0439dbe6f..e62d3445f9 100644 --- a/src/BenchmarkDotNet/Diagnosers/PerfCollectProfiler.cs +++ b/src/BenchmarkDotNet/Diagnosers/PerfCollectProfiler.cs @@ -73,7 +73,7 @@ private async IAsyncEnumerable ValidateAsyncCore(ValidationPara public void DisplayResults(ILogger logger) { - if (!benchmarkToTraceFile.Any()) + if (benchmarkToTraceFile.Count == 0) return; logger.WriteLineInfo($"Exported {benchmarkToTraceFile.Count} trace file(s). Example:"); @@ -227,7 +227,7 @@ private async ValueTask EnsureSymbolsForNativeRuntime(DiagnoserActionParameters .Distinct() .ToArray(); - if (!missingSymbols.Any()) + if (missingSymbols.Length == 0) { return; // the symbol files are already where we need them! } diff --git a/src/BenchmarkDotNet/Disassemblers/DataContracts.cs b/src/BenchmarkDotNet/Disassemblers/DataContracts.cs index c7b5ddf428..0b0cb5840a 100644 --- a/src/BenchmarkDotNet/Disassemblers/DataContracts.cs +++ b/src/BenchmarkDotNet/Disassemblers/DataContracts.cs @@ -252,7 +252,7 @@ internal static Version ParseVersion(string targetFrameworkMoniker) } string versionToParse = targetFrameworkMoniker.Substring(firstDigit, lastDigit - firstDigit + 1); - if (!versionToParse.Contains(".")) // Full .NET Framework (net48 etc) + if (!versionToParse.Contains('.')) // Full .NET Framework (net48 etc) versionToParse = string.Join(".", versionToParse.ToCharArray()); return Version.Parse(versionToParse); diff --git a/src/BenchmarkDotNet/Disassemblers/DisassemblyDiagnoser.cs b/src/BenchmarkDotNet/Disassemblers/DisassemblyDiagnoser.cs index 9ca2cbda84..8d8d408f70 100644 --- a/src/BenchmarkDotNet/Disassemblers/DisassemblyDiagnoser.cs +++ b/src/BenchmarkDotNet/Disassemblers/DisassemblyDiagnoser.cs @@ -217,7 +217,22 @@ private static IEnumerable GetExporters(Dictionary disassembly.Methods.Sum(method => method.Maps.Sum(map => map.SourceCodes.OfType().Sum(asm => asm.InstructionLength))); + { + long total = 0; + + foreach (var method in disassembly.Methods) + { + foreach (var map in method.Maps) + { + foreach (var asm in map.SourceCodes.OfType()) + { + total += asm.InstructionLength; + } + } + } + + return total; + } InProcessDiagnoserHandlerData IInProcessDiagnoser.GetHandlerData(BenchmarkCase benchmarkCase) { diff --git a/src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs b/src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs index df264877c1..ddaf2b2ca1 100644 --- a/src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs +++ b/src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs @@ -78,7 +78,7 @@ internal static DisassemblyResult Parse(IReadOnlyList input, string meth if (TryParseInstruction(line, out var instruction)) instructions.Add(instruction); - while (instructions.Any() && instructions.Last().Text == "nop") + while (instructions.Count != 0 && instructions.Last().Text == "nop") instructions.RemoveAt(instructions.Count - 1); return new DisassemblyResult diff --git a/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs b/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs index 9eed15bd41..d97a230be1 100644 --- a/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs +++ b/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs @@ -180,7 +180,7 @@ internal static bool TryGetVersionFromProductInfo(string productVersion, string { if (productVersion.IsNotBlank() && productName.IsNotBlank()) { - if (productName.IndexOf(".NET Core", StringComparison.OrdinalIgnoreCase) >= 0) + if (productName.Contains(".NET Core", StringComparison.OrdinalIgnoreCase)) { string parsableVersion = GetParsableVersionPart(productVersion); if (Version.TryParse(productVersion, out version) || Version.TryParse(parsableVersion, out version)) @@ -190,7 +190,7 @@ internal static bool TryGetVersionFromProductInfo(string productVersion, string } // yes, .NET Core 2.X has a product name == .NET Framework... - if (productName.IndexOf(".NET Framework", StringComparison.OrdinalIgnoreCase) >= 0) + if (productName.Contains(".NET Framework", StringComparison.OrdinalIgnoreCase)) { const string releaseVersionPrefix = "release/"; int releaseVersionIndex = productVersion.IndexOf(releaseVersionPrefix, StringComparison.Ordinal); diff --git a/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs b/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs index 1bfaf346ce..e69f3fd78c 100644 --- a/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/ReflectionExtensions.cs @@ -201,7 +201,7 @@ internal static bool ContainsRunnableBenchmarks(this Type type) if (typeInfo.IsAbstract || typeInfo.IsGenericType && !IsRunnableGenericType(typeInfo)) return false; - return typeInfo.GetBenchmarks().Any(); + return typeInfo.GetBenchmarks().Length != 0; } private static MethodInfo[] GetBenchmarks(this TypeInfo typeInfo) @@ -254,11 +254,11 @@ internal static bool IsStackOnlyWithImplicitCast(this Type argumentType, [NotNul var instanceType = argumentInstance.GetType(); - var implicitCastsDefinedInArgumentInstance = instanceType.GetMethods().Where(method => method.Name == "op_Implicit" && method.GetParameters().Any()).ToArray(); + var implicitCastsDefinedInArgumentInstance = instanceType.GetMethods().Where(method => method.Name == "op_Implicit" && method.GetParameters().Length != 0).ToArray(); if (implicitCastsDefinedInArgumentInstance.Any(implicitCast => implicitCast.ReturnType == argumentType && implicitCast.GetParameters().All(p => p.ParameterType == instanceType))) return true; - var implicitCastsDefinedInArgumentType = argumentType.GetMethods().Where(method => method.Name == "op_Implicit" && method.GetParameters().Any()).ToArray(); + var implicitCastsDefinedInArgumentType = argumentType.GetMethods().Where(method => method.Name == "op_Implicit" && method.GetParameters().Length != 0).ToArray(); if (implicitCastsDefinedInArgumentType.Any(implicitCast => implicitCast.ReturnType == argumentType && implicitCast.GetParameters().All(p => p.ParameterType == instanceType))) return true; @@ -267,10 +267,10 @@ internal static bool IsStackOnlyWithImplicitCast(this Type argumentType, [NotNul private static bool IsRunnableGenericType(TypeInfo typeInfo) => // if it is an open generic - there must be GenericBenchmark attributes - (!typeInfo.IsGenericTypeDefinition || typeInfo.GenericTypeArguments.Any() || typeInfo.GetCustomAttributes(true).OfType().Any()) + (!typeInfo.IsGenericTypeDefinition || typeInfo.GenericTypeArguments.Length != 0 || typeInfo.GetCustomAttributes(true).OfType().Any()) && typeInfo.DeclaredConstructors.Any(ctor => ctor.IsPublic && ctor.GetParameters().Length == 0); // we need public parameterless ctor to create it - internal static bool IsLinqPad(this Assembly assembly) => assembly.FullName!.IndexOf("LINQPAD", StringComparison.OrdinalIgnoreCase) >= 0; + internal static bool IsLinqPad(this Assembly assembly) => assembly.FullName!.Contains("LINQPAD", StringComparison.OrdinalIgnoreCase); internal static bool IsByRefLike(this Type type) #if NETSTANDARD2_0 diff --git a/src/BenchmarkDotNet/Helpers/GenericBenchmarksBuilder.cs b/src/BenchmarkDotNet/Helpers/GenericBenchmarksBuilder.cs index 471087713c..e0a336960f 100644 --- a/src/BenchmarkDotNet/Helpers/GenericBenchmarksBuilder.cs +++ b/src/BenchmarkDotNet/Helpers/GenericBenchmarksBuilder.cs @@ -18,7 +18,7 @@ internal static Type[] GetRunnableBenchmarks(IEnumerable types) .Select(x => x.GenericTypeArguments) .ToArray(); - if (typeArguments.Any()) + if (typeArguments.Length != 0) return BuildGenericTypes(type, typeArguments); return [(true, type)]; diff --git a/src/BenchmarkDotNet/Helpers/SectionsHelper.cs b/src/BenchmarkDotNet/Helpers/SectionsHelper.cs index a91fdd380f..c4ad06f74b 100644 --- a/src/BenchmarkDotNet/Helpers/SectionsHelper.cs +++ b/src/BenchmarkDotNet/Helpers/SectionsHelper.cs @@ -10,7 +10,7 @@ public static Dictionary ParseSection(string? content, char sepa var list = content?.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); if (list != null) foreach (string line in list) - if (line.IndexOf(separator) != -1) + if (line.Contains(separator)) { var lineParts = line.Split(separator); if (lineParts.Length >= 2) diff --git a/src/BenchmarkDotNet/Helpers/UserInteractionHelper.cs b/src/BenchmarkDotNet/Helpers/UserInteractionHelper.cs index 01cbff149b..b207c33eab 100644 --- a/src/BenchmarkDotNet/Helpers/UserInteractionHelper.cs +++ b/src/BenchmarkDotNet/Helpers/UserInteractionHelper.cs @@ -19,7 +19,7 @@ internal static class UserInteractionHelper /// public static string EscapeCommandExample(string input) { - return !OsDetector.IsWindows() && input.IndexOf('*') >= 0 ? $"'{input}'" : input; + return !OsDetector.IsWindows() && input.Contains('*') ? $"'{input}'" : input; } } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Loggers/ConsoleLogger.cs b/src/BenchmarkDotNet/Loggers/ConsoleLogger.cs index 0354a6b032..0d5cbb9be5 100644 --- a/src/BenchmarkDotNet/Loggers/ConsoleLogger.cs +++ b/src/BenchmarkDotNet/Loggers/ConsoleLogger.cs @@ -71,7 +71,7 @@ private void Write(LogKind logKind, Action write, string text) } private ConsoleColor GetColor(LogKind logKind) => - colorScheme.ContainsKey(logKind) ? colorScheme[logKind] : DefaultColor; + colorScheme.TryGetValue(logKind, out ConsoleColor value) ? value : DefaultColor; private static Dictionary CreateColorfulScheme() => new Dictionary diff --git a/src/BenchmarkDotNet/Mathematics/LegacyConfidenceInterval.cs b/src/BenchmarkDotNet/Mathematics/LegacyConfidenceInterval.cs index a9f71dad57..1e3d5466bc 100644 --- a/src/BenchmarkDotNet/Mathematics/LegacyConfidenceInterval.cs +++ b/src/BenchmarkDotNet/Mathematics/LegacyConfidenceInterval.cs @@ -157,7 +157,7 @@ public string ToString(Func formatter, bool showLevel = true) builder.Append(formatter(Lower)); builder.Append("; "); builder.Append(formatter(Upper)); - builder.Append("]"); + builder.Append(']'); builder.Append(GetLevelHint(showLevel)); return builder.ToString(); } diff --git a/src/BenchmarkDotNet/Mathematics/PercentileValues.cs b/src/BenchmarkDotNet/Mathematics/PercentileValues.cs index 5c8e45a838..a6a196a3d1 100644 --- a/src/BenchmarkDotNet/Mathematics/PercentileValues.cs +++ b/src/BenchmarkDotNet/Mathematics/PercentileValues.cs @@ -52,7 +52,7 @@ public string ToString(Func formatter) builder.Append(formatter(P50)); builder.Append("]; [P100: "); builder.Append(formatter(P100)); - builder.Append("]"); + builder.Append(']'); return builder.ToString(); } diff --git a/src/BenchmarkDotNet/Portability/StringExtensions.cs b/src/BenchmarkDotNet/Portability/StringExtensions.cs index cd374f2787..4585578c61 100644 --- a/src/BenchmarkDotNet/Portability/StringExtensions.cs +++ b/src/BenchmarkDotNet/Portability/StringExtensions.cs @@ -4,6 +4,6 @@ internal static class StringExtensions { internal static bool EqualsWithIgnoreCase(this string left, string right) => left != null && left.Equals(right, StringComparison.InvariantCultureIgnoreCase); - internal static bool ContainsWithIgnoreCase(this string text, string word) => text != null && text.IndexOf(word, StringComparison.InvariantCultureIgnoreCase) >= 0; + internal static bool ContainsWithIgnoreCase(this string text, string word) => text != null && text.Contains(word, StringComparison.InvariantCultureIgnoreCase); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Reports/DisplayPrecisionManager.cs b/src/BenchmarkDotNet/Reports/DisplayPrecisionManager.cs index a8e7a4ed1e..75010ae439 100644 --- a/src/BenchmarkDotNet/Reports/DisplayPrecisionManager.cs +++ b/src/BenchmarkDotNet/Reports/DisplayPrecisionManager.cs @@ -19,15 +19,16 @@ internal class DisplayPrecisionManager /// public int GetPrecision(SummaryStyle summaryStyle, IStatisticColumn column, IStatisticColumn? parentColumn = null) { - if (!precision.ContainsKey(column.Id)) - { - var values = column.GetAllValues(summary, summaryStyle); - precision[column.Id] = parentColumn != null - ? CalcPrecision(values, GetPrecision(summaryStyle, parentColumn)) - : CalcPrecision(values); - } - - return precision[column.Id]; + if (precision.TryGetValue(column.Id, out int value)) + return value; + + var values = column.GetAllValues(summary, summaryStyle); + value = parentColumn != null + ? CalcPrecision(values, GetPrecision(summaryStyle, parentColumn)) + : CalcPrecision(values); + precision[column.Id] = value; + + return value; } internal static int CalcPrecision(IList values) diff --git a/src/BenchmarkDotNet/Reports/SummaryTable.cs b/src/BenchmarkDotNet/Reports/SummaryTable.cs index 3e892329bb..26dca679c1 100644 --- a/src/BenchmarkDotNet/Reports/SummaryTable.cs +++ b/src/BenchmarkDotNet/Reports/SummaryTable.cs @@ -118,7 +118,7 @@ public SummaryTableColumn(SummaryTable table, int index, IColumn column, bool hi Index = index; Header = table.FullHeader[index]; Content = table.FullContent.Select(line => line[index]).ToArray(); - Width = Math.Max(Header.Length, Content.Any() ? Content.Max(line => line.Length) : 0) + 1; + Width = Math.Max(Header.Length, Content.Length != 0 ? Content.Max(line => line.Length) : 0) + 1; IsDefault = table.IsDefault[index]; OriginalColumn = column; diff --git a/src/BenchmarkDotNet/Reports/SummaryTableExtensions.cs b/src/BenchmarkDotNet/Reports/SummaryTableExtensions.cs index 5f10a60d64..2a611c246a 100644 --- a/src/BenchmarkDotNet/Reports/SummaryTableExtensions.cs +++ b/src/BenchmarkDotNet/Reports/SummaryTableExtensions.cs @@ -14,7 +14,7 @@ internal static class SummaryTableExtensions public static async ValueTask PrintCommonColumnsAsync(this SummaryTable table, StreamOrLoggerWriter writer, CancellationToken cancellationToken) { var commonColumns = table.Columns.Where(c => c.IsCommon).ToArray(); - if (commonColumns.Any()) + if (commonColumns.Length != 0) { int paramsOnLine = 0; foreach (var column in commonColumns) diff --git a/src/BenchmarkDotNet/Running/BenchmarkConverter.cs b/src/BenchmarkDotNet/Running/BenchmarkConverter.cs index bcc40e93ad..077a9aa05e 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkConverter.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkConverter.cs @@ -260,7 +260,7 @@ private static ImmutableArray GetFilteredBenchmarks(IEnumerable() && !methodInfo.HasAttribute()) + if (methodInfo.GetParameters().Length != 0 && !methodInfo.HasAttribute() && !methodInfo.HasAttribute()) throw new InvalidBenchmarkDeclarationException($"{methodType} method {methodInfo.Name} has incorrect signature.\nMethod shouldn't have any arguments."); } diff --git a/src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs b/src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs index 9a744e6ee1..244e4b2e5e 100644 --- a/src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs +++ b/src/BenchmarkDotNet/Running/BenchmarkRunnerClean.cs @@ -374,12 +374,12 @@ private static async ValueTask PrintSummary(ILogger logger, ImmutableConfig conf bool needToShowTimeLegend = summary.Table.Columns.Any(c => c.NeedToShow && c.OriginalColumn.UnitType == UnitType.Time); var effectiveTimeUnit = needToShowTimeLegend ? summary.Table.EffectiveSummaryStyle.TimeUnit : null; - if (columnWithLegends.Any() || effectiveTimeUnit != null) + if (columnWithLegends.Length != 0 || effectiveTimeUnit != null) { logger.WriteLine(); logger.WriteLineHeader("// * Legends *"); int maxNameWidth = 0; - if (columnWithLegends.Any()) + if (columnWithLegends.Length != 0) maxNameWidth = Math.Max(maxNameWidth, columnWithLegends.Select(c => c.ColumnName.Length).Max()); if (effectiveTimeUnit != null) maxNameWidth = Math.Max(maxNameWidth, effectiveTimeUnit.GetAbbreviation().ToString(cultureInfo).Length + 2); @@ -793,7 +793,7 @@ private static ILogger CreateCompositeLogger(BenchmarkRunInfo[] benchmarkRunInfo void AddLogger(ILogger logger) { - if (!loggers.ContainsKey(logger.Id) || loggers[logger.Id].Priority < logger.Priority) + if (!loggers.TryGetValue(logger.Id, out ILogger? value) || value.Priority < logger.Priority) loggers[logger.Id] = logger; } diff --git a/src/BenchmarkDotNet/Running/TypeFilter.cs b/src/BenchmarkDotNet/Running/TypeFilter.cs index b9420915b5..00d0b98ab4 100644 --- a/src/BenchmarkDotNet/Running/TypeFilter.cs +++ b/src/BenchmarkDotNet/Running/TypeFilter.cs @@ -63,7 +63,7 @@ public static (bool allTypesValid, IReadOnlyList runnable) GetTypesWithRun public static BenchmarkRunInfo[] Filter(IConfig effectiveConfig, IEnumerable types) => types .Select(type => BenchmarkConverter.TypeToBenchmarks(type, effectiveConfig)) - .Where(info => info.BenchmarksCases.Any()) + .Where(info => info.BenchmarksCases.Length != 0) .ToArray(); } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Toolchains/Roslyn/Builder.cs b/src/BenchmarkDotNet/Toolchains/Roslyn/Builder.cs index 496e2add38..3f1ea21e07 100644 --- a/src/BenchmarkDotNet/Toolchains/Roslyn/Builder.cs +++ b/src/BenchmarkDotNet/Toolchains/Roslyn/Builder.cs @@ -67,7 +67,7 @@ private async ValueTask Build(GenerateResult generateResult, BuildP var (result, missingReferences) = Build(generateResult, buildPartition, syntaxTree, compilationOptions, references, cancellationToken); - if (result.IsBuildSuccess || !missingReferences.Any()) + if (result.IsBuildSuccess || missingReferences.Length == 0) return result; var withMissingReferences = references.Union(missingReferences.Select(assemblyMetadata => assemblyMetadata.GetReference())); diff --git a/src/BenchmarkDotNet/Validators/DotNetSdkValidator.cs b/src/BenchmarkDotNet/Validators/DotNetSdkValidator.cs index 369265cb92..6fe706ba37 100644 --- a/src/BenchmarkDotNet/Validators/DotNetSdkValidator.cs +++ b/src/BenchmarkDotNet/Validators/DotNetSdkValidator.cs @@ -92,7 +92,7 @@ private static IEnumerable GetInstalledDotNetSdks(string? customDotNetC { var lines = output.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); - var versions = new List(lines.Count()); + var versions = new List(lines.Length); foreach (var line in lines) { // Version.TryParse does not handle things like 3.0.0-WORD, so this will get just the 3.0.0 part diff --git a/tests/BenchmarkDotNet.IntegrationTests/DisassemblyDiagnoserTests.cs b/tests/BenchmarkDotNet.IntegrationTests/DisassemblyDiagnoserTests.cs index 26720c6c41..6978428fae 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/DisassemblyDiagnoserTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/DisassemblyDiagnoserTests.cs @@ -190,7 +190,7 @@ private IConfig CreateConfig(Jit jit, Platform platform, IToolchain toolchain, I private void AssertDisassemblyResult(DisassemblyResult result, string methodSignature) { Assert.Contains(methodSignature, result.Methods.Select(m => m.Name.Split('.').Last()).ToArray()); - Assert.Contains(result.Methods.Single(m => m.Name.EndsWith(methodSignature)).Maps, map => map.SourceCodes.Any()); + Assert.Contains(result.Methods.Single(m => m.Name.EndsWith(methodSignature)).Maps, map => map.SourceCodes.Length != 0); } } } \ No newline at end of file diff --git a/tests/BenchmarkDotNet.IntegrationTests/InProcessDiagnoserTests.cs b/tests/BenchmarkDotNet.IntegrationTests/InProcessDiagnoserTests.cs index a722950b42..2349127e7e 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/InProcessDiagnoserTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/InProcessDiagnoserTests.cs @@ -23,7 +23,7 @@ public enum ToolchainType private static IEnumerable GetRunModeCombinations(int count) { - var runModes = (RunMode[])Enum.GetValues(typeof(RunMode)); + var runModes = Enum.GetValues(); if (count == 1) { @@ -49,7 +49,7 @@ private static IEnumerable GetRunModeCombinations(int count) public static IEnumerable GetTestCombinations() { - var toolchains = (ToolchainType[])Enum.GetValues(typeof(ToolchainType)); + var toolchains = Enum.GetValues(); var counts = new[] { 1, 3 }; foreach (var toolchain in toolchains) diff --git a/tests/BenchmarkDotNet.IntegrationTests/JitListenerTests.cs b/tests/BenchmarkDotNet.IntegrationTests/JitListenerTests.cs index ca6d6c8765..0cb4b819c2 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/JitListenerTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/JitListenerTests.cs @@ -1,6 +1,7 @@ using System.Reflection; using System.Runtime.CompilerServices; using BenchmarkDotNet.Engines; +using BenchmarkDotNet.Helpers; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Portability; using BenchmarkDotNet.Reports; @@ -410,9 +411,9 @@ private static void RunJitStageToCompletion(JitListener? listener, MethodInfo[] var measurements = stage.GetMeasurementList(); while (stage.GetShouldRunIteration(measurements, out var data)) { - data.setupAction().GetAwaiter().GetResult(); - data.workloadAction(data.invokeCount / data.unrollFactor, null!).GetAwaiter().GetResult(); - data.cleanupAction().GetAwaiter().GetResult(); + data.setupAction().GetResult(); + data.workloadAction(data.invokeCount / data.unrollFactor, null!).GetResult(); + data.cleanupAction().GetResult(); // A zero-time measurement keeps the stage out of its "long-running benchmark" early-exit // (iterationTime / 0 == Infinity, and Infinity < 1.5 is false). measurements.Add(new Measurement(1, data.mode, data.stage, data.index, data.invokeCount, 0d)); diff --git a/tests/BenchmarkDotNet.IntegrationTests/JitOptimizationsTests.cs b/tests/BenchmarkDotNet.IntegrationTests/JitOptimizationsTests.cs index 735407181f..ab0f6d6b1f 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/JitOptimizationsTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/JitOptimizationsTests.cs @@ -33,7 +33,7 @@ public async Task UserGetsNoWarningWhenOnlyOptimizedDllAreReferenced() var warnings = await JitOptimizationsValidator.DontFailOnError.ValidateAsync(benchmarksWithOptimizedDll).ToArrayAsync(); - if (warnings.Any()) + if (warnings.Length != 0) { output.WriteLine("*** Warnings ***"); foreach (var warning in warnings) diff --git a/tests/BenchmarkDotNet.IntegrationTests/RunStrategyTests.cs b/tests/BenchmarkDotNet.IntegrationTests/RunStrategyTests.cs index e263a5ee05..382ecd9b0c 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/RunStrategyTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/RunStrategyTests.cs @@ -24,7 +24,7 @@ public void RunStrategiesAreSupported() var results = CanExecute(config); - Assert.Equal(6, results.BenchmarksCases.Count()); + Assert.Equal(6, results.BenchmarksCases.Length); Assert.Equal(1, results.BenchmarksCases.Count(b => b.Job.Run.RunStrategy == RunStrategy.ColdStart && b.Descriptor.WorkloadMethod.Name == "BenchmarkWithVoid")); Assert.Equal(1, results.BenchmarksCases.Count(b => b.Job.Run.RunStrategy == RunStrategy.ColdStart && b.Descriptor.WorkloadMethod.Name == "BenchmarkWithReturnValue")); diff --git a/tests/BenchmarkDotNet.IntegrationTests/RunningEmptyBenchmarkTests.cs b/tests/BenchmarkDotNet.IntegrationTests/RunningEmptyBenchmarkTests.cs index b437ae35d5..abf5dd8702 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/RunningEmptyBenchmarkTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/RunningEmptyBenchmarkTests.cs @@ -90,7 +90,7 @@ public void TypeWithoutBenchmarkAttribute_ThrowsValidationError_WhenNoBenchmarkA { GetConfigWithLogger(out var logger, out var config); - var summary = BenchmarkRunner.Run(typeof(EmptyBenchmark), config, args); + var summary = BenchmarkRunner.Run(config, args); if (args == null) { @@ -115,7 +115,7 @@ public void TypeWithBenchmarkAttribute_RunsSuccessfully(string[]? args) { GetConfigWithLogger(out var logger, out var config); - var summaries = BenchmarkRunner.Run(typeof(NotEmptyBenchmark), config, args); + var summaries = BenchmarkRunner.Run(config, args); Assert.False(summaries.HasCriticalValidationErrors); Assert.DoesNotContain(summaries.ValidationErrors, validationError => validationError.Message == GetValidationErrorForType(typeof(NotEmptyBenchmark))); Assert.DoesNotContain(GetValidationErrorForType(typeof(NotEmptyBenchmark)), logger.GetLog()); diff --git a/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs b/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs index e9119a7594..a9c70fec16 100644 --- a/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs +++ b/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs @@ -218,7 +218,7 @@ public void TheDefaultFilePathShouldBeUsedWhenAnAssemblyLocationIsEmpty() var projectGenerator = new SteamLoadedBuildPartition("netcoreapp3.1", "", "", "", true); string binariesPath = projectGenerator.ResolvePathForBinaries(new BuildPartition(benchmarks, new Resolver()), programName); - string expectedPath = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "BenchmarkDotNet.Bin"), programName); + string expectedPath = Path.Combine(Directory.GetCurrentDirectory(), "BenchmarkDotNet.Bin", programName); Assert.Equal(expectedPath, binariesPath); } diff --git a/tests/BenchmarkDotNet.Tests/Exporters/XmlSerializerTests.cs b/tests/BenchmarkDotNet.Tests/Exporters/XmlSerializerTests.cs index d3fa3d0e8f..b563797ce3 100644 --- a/tests/BenchmarkDotNet.Tests/Exporters/XmlSerializerTests.cs +++ b/tests/BenchmarkDotNet.Tests/Exporters/XmlSerializerTests.cs @@ -241,11 +241,11 @@ public void WriteStartDocument() public void WriteElementString(string localName, string value) { writer.Append(localName); - writer.Append(" "); + writer.Append(' '); writer.Append(value); - writer.Append(" "); + writer.Append(' '); writer.Append(localName); - writer.Append(" "); + writer.Append(' '); } public void WriteEndDocument() @@ -257,14 +257,14 @@ public void WriteEndElement() { var endElement = openElements.Pop(); writer.Append(endElement); - writer.Append(" "); + writer.Append(' '); } public void WriteStartElement(string localName) { openElements.Push(localName); writer.Append(localName); - writer.Append(" "); + writer.Append(' '); } public override string ToString() => writer.ToString(); diff --git a/tests/BenchmarkDotNet.Tests/Reports/DisplayPrecisionManagerTests.cs b/tests/BenchmarkDotNet.Tests/Reports/DisplayPrecisionManagerTests.cs index 20bb87fa88..35dd155337 100644 --- a/tests/BenchmarkDotNet.Tests/Reports/DisplayPrecisionManagerTests.cs +++ b/tests/BenchmarkDotNet.Tests/Reports/DisplayPrecisionManagerTests.cs @@ -66,7 +66,7 @@ public void GeneralTest(string testDataName) string strParent = parentPrecision.HasValue ? 1234.5678.ToString("N" + parentPrecision, TestCultureInfo.Instance) : "NA"; var strValues = testData.Values.Select(v => v.ToString("N" + actualPrecision, TestCultureInfo.Instance)).ToList(); - int maxWidth = strValues.Any() ? Math.Max(strValues.Max(s => s.Length), strParent.Length) + 6 : 0; + int maxWidth = strValues.Count != 0 ? Math.Max(strValues.Max(s => s.Length), strParent.Length) + 6 : 0; int parentWidth = maxWidth - (actualPrecision - parentPrecision) ?? 0; output.WriteLine("******************************"); diff --git a/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs b/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs index 535152425b..768f2c70b0 100644 --- a/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs +++ b/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs @@ -75,7 +75,7 @@ public async Task Benchmark_Class_Modifers_Must_Be_Public(Type type, bool hasErr { var validationErrors = await CompilationValidator.FailOnError.ValidateAsync(BenchmarkConverter.TypeToBenchmarks(type)).ToArrayAsync(); - Assert.Equal(hasErrors, validationErrors.Any()); + Assert.Equal(hasErrors, validationErrors.Length != 0); } [Theory] @@ -85,7 +85,7 @@ public async Task Benchmark_Class_Methods_Must_Be_Non_Static(Type type, bool has { var validationErrors = await CompilationValidator.FailOnError.ValidateAsync(BenchmarkConverter.TypeToBenchmarks(type)).ToArrayAsync(); - Assert.Equal(hasErrors, validationErrors.Any()); + Assert.Equal(hasErrors, validationErrors.Length != 0); } [Theory] @@ -108,7 +108,7 @@ public async Task Benchmark_Class_Generic_Argument_Must_Be_Public(Type type, boo var validationErrors = await CompilationValidator.FailOnError.ValidateAsync(BenchmarkConverter.TypeToBenchmarks(constructed)).ToArrayAsync(); // Assert - Assert.Equal(hasErrors, validationErrors.Any()); + Assert.Equal(hasErrors, validationErrors.Length != 0); } private static Delegate BuildDummyMethod(string name) diff --git a/tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementCheckerTests.cs b/tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementCheckerTests.cs index f06d5483a5..5462d5ea1d 100644 --- a/tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementCheckerTests.cs +++ b/tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementCheckerTests.cs @@ -6,7 +6,7 @@ public class EnvRequirementCheckerTests [Fact] public void AllEnvRequirementsAreSupported() { - foreach (var envRequirement in Enum.GetValues(typeof(EnvRequirement)).Cast()) + foreach (var envRequirement in Enum.GetValues().Cast()) EnvRequirementChecker.GetSkip(envRequirement); } } \ No newline at end of file