Skip to content

Commit 269a1ac

Browse files
authored
Reduce allocations. (#1080)
1 parent 150561b commit 269a1ac

28 files changed

+573
-268
lines changed

src/System.CommandLine.Benchmarks/CommandLine/Perf_Parser_NestedCommands.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,9 @@ public void SetupRootCommand()
5656

5757
// Choose only one path from the commands tree for the test arguments string
5858
ISymbol currentCmd = rootCommand;
59-
while (currentCmd.Children.Any())
59+
while (currentCmd.Children.Count > 0)
6060
{
61-
currentCmd = currentCmd.Children.First();
61+
currentCmd = currentCmd.Children[0];
6262
_testSymbolsAsString = string.Join(" ", _testSymbolsAsString, currentCmd.Name);
6363
}
6464

src/System.CommandLine.Benchmarks/RecommendedConfig.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ namespace System.CommandLine.Benchmarks
1414
{
1515
public static class RecommendedConfig
1616
{
17+
#pragma warning disable CA1801 // Review unused parameters
1718
public static IConfig Create(DirectoryInfo artifactsPath, ImmutableHashSet<string> mandatoryCategories)
19+
#pragma warning restore CA1801 // Review unused parameters
20+
#pragma warning disable CA1062 // Validate arguments of public methods
1821
=> DefaultConfig.Instance
1922
.With(Job.Default
2023
.WithWarmupCount(1)
@@ -26,5 +29,6 @@ public static IConfig Create(DirectoryInfo artifactsPath, ImmutableHashSet<strin
2629
.With(MemoryDiagnoser.Default)
2730
.With(JsonExporter.Full)
2831
.With(StatisticColumn.Median, StatisticColumn.Min, StatisticColumn.Max);
32+
#pragma warning restore CA1062 // Validate arguments of public methods
2933
}
3034
}

src/System.CommandLine.Benchmarks/System.CommandLine.Benchmarks.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
</ItemGroup>
3737

3838
<ItemGroup>
39-
<PackageReference Include="BenchmarkDotNet" Version="0.11.5" />
39+
<PackageReference Include="BenchmarkDotNet" Version="0.12.0" />
4040
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="3.5.0" />
4141
</ItemGroup>
4242

src/System.CommandLine.DragonFruit/XmlDocReader.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ public bool TryGetMethodDescription(MethodInfo info, out CommandHelpMetadata com
5151
commandHelpMetadata = null;
5252

5353
var sb = new StringBuilder();
54+
5455
sb.Append("M:");
5556
AppendTypeName(sb, info.DeclaringType);
5657
sb.Append(".")

src/System.CommandLine.Rendering/Ansi.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public static class Background
5151
public static AnsiControlCode LightCyan { get; } = $"{Esc}[106m";
5252
public static AnsiControlCode LightGray { get; } = $"{Esc}[107m";
5353

54-
public static AnsiControlCode Rgb(byte r, byte g, byte b) => $"{Esc}[48;2;{r};{g};{b}m";
54+
public static AnsiControlCode Rgb(byte r, byte g, byte b) => $"{Esc}[48;2;{r.ToString()};{g.ToString()};{b.ToString()}m";
5555
}
5656

5757
[DebuggerStepThrough]
@@ -76,7 +76,7 @@ public static class Foreground
7676
public static AnsiControlCode LightCyan { get; } = $"{Esc}[96m";
7777
public static AnsiControlCode LightGray { get; } = $"{Esc}[97m";
7878

79-
public static AnsiControlCode Rgb(byte r, byte g, byte b) => $"{Esc}[38;2;{r};{g};{b}m";
79+
public static AnsiControlCode Rgb(byte r, byte g, byte b) => $"{Esc}[38;2;{r.ToString()};{g.ToString()};{b.ToString()}m";
8080
}
8181
}
8282

@@ -87,13 +87,13 @@ public static class Cursor
8787
[DebuggerStepThrough]
8888
public static class Move
8989
{
90-
public static AnsiControlCode Up(int lines = 1) => $"{Esc}[{lines}A";
91-
public static AnsiControlCode Down(int lines = 1) => $"{Esc}[{lines}B";
92-
public static AnsiControlCode Right(int columns = 1) => $"{Esc}[{columns}C";
93-
public static AnsiControlCode Left(int columns = 1) => $"{Esc}[{columns}D";
94-
public static AnsiControlCode NextLine(int line = 1) => $"{Esc}[{line}E";
90+
public static AnsiControlCode Up(int lines = 1) => $"{Esc}[{lines.ToString()}A";
91+
public static AnsiControlCode Down(int lines = 1) => $"{Esc}[{lines.ToString()}B";
92+
public static AnsiControlCode Right(int columns = 1) => $"{Esc}[{columns.ToString()}C";
93+
public static AnsiControlCode Left(int columns = 1) => $"{Esc}[{columns.ToString()}D";
94+
public static AnsiControlCode NextLine(int line = 1) => $"{Esc}[{line.ToString()}E";
9595
public static AnsiControlCode ToUpperLeftCorner { get; } = $"{Esc}[H";
96-
public static AnsiControlCode ToLocation(int? left = null, int? top = null) => $"{Esc}[{top ?? 1};{left ?? 1}H";
96+
public static AnsiControlCode ToLocation(int? left = null, int? top = null) => $"{Esc}[{top.GetValueOrDefault(1)};{left.GetValueOrDefault(1).ToString()}H";
9797
}
9898

9999
[DebuggerStepThrough]

src/System.CommandLine.Rendering/Views/GridView.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ public void SetChild(View child, int column, int row)
3636

3737
public void SetColumns(params ColumnDefinition[] columns)
3838
{
39-
if (Children.Any())
39+
if (Children.Count > 0)
4040
{
4141
throw new InvalidOperationException("Cannot change columns once children are added");
4242
}
43-
if (columns?.Any() != true)
43+
if ((columns is null) || (columns.Length == 0))
4444
{
4545
throw new ArgumentException("Must specify at least one column", nameof(columns));
4646
}
@@ -51,11 +51,11 @@ public void SetColumns(params ColumnDefinition[] columns)
5151

5252
public void SetRows(params RowDefinition[] rows)
5353
{
54-
if (Children.Any())
54+
if (Children.Count > 0)
5555
{
5656
throw new InvalidOperationException("Cannot change rows once children are added");
5757
}
58-
if (rows?.Any() != true)
58+
if ((rows is null) || (rows.Length == 0))
5959
{
6060
throw new ArgumentException("Must specify at least one row", nameof(rows));
6161
}

src/System.CommandLine.Rendering/Views/LayoutView.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public virtual void Add(T child)
2929

3030
public virtual void Clear()
3131
{
32-
while (Children.Any())
32+
while (_children.Count != 0)
3333
{
3434
Remove(Children[0]);
3535
}

src/System.CommandLine.Suggest/FileSuggestionRegistration.cs

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Collections.Generic;
55
using System.IO;
66
using System.Linq;
7+
using System.Text;
78
using static System.Environment;
89

910
namespace System.CommandLine.Suggest
@@ -30,7 +31,7 @@ public FileSuggestionRegistration(string registrationsConfigurationFilePath = nu
3031
}
3132

3233
var userProfile = GetFolderPath(SpecialFolder.UserProfile);
33-
34+
3435
_registrationConfigurationFilePath = Path.Combine(userProfile, RegistrationFileName);
3536
}
3637

@@ -47,11 +48,19 @@ public Registration FindRegistration(FileInfo soughtExecutable)
4748
return null;
4849
}
4950

50-
var completionTarget =
51-
File.ReadAllLines(_registrationConfigurationFilePath).LastOrDefault(line =>
52-
line.StartsWith(soughtExecutable.FullName, StringComparison.OrdinalIgnoreCase));
51+
string completionTarget = null;
52+
using (var sr = new StreamReader(_registrationConfigurationFilePath, Encoding.UTF8))
53+
{
54+
while (sr.ReadLine() is string line)
55+
{
56+
if (line.StartsWith(soughtExecutable.FullName, StringComparison.OrdinalIgnoreCase))
57+
{
58+
completionTarget = line;
59+
}
60+
}
61+
}
5362

54-
if (completionTarget == null)
63+
if (completionTarget is null)
5564
{
5665
// Completion provider not found!
5766
return null;
@@ -66,13 +75,17 @@ public IEnumerable<Registration> FindAllRegistrations()
6675

6776
if (_registrationConfigurationFilePath != null && File.Exists(_registrationConfigurationFilePath))
6877
{
69-
allRegistration
70-
.AddRange(File
71-
.ReadAllLines(_registrationConfigurationFilePath)
72-
.Select(l => l.Trim())
73-
.Where(l => l.Any())
74-
.Select(item => new Registration(item))
75-
);
78+
using (var sr = new StreamReader(_registrationConfigurationFilePath, Encoding.UTF8))
79+
{
80+
string line;
81+
while ((line = sr.ReadLine()) != null)
82+
{
83+
if (!string.IsNullOrWhiteSpace(line))
84+
{
85+
allRegistration.Add(new Registration(line.Trim()));
86+
}
87+
}
88+
}
7689
}
7790

7891
return allRegistration;

src/System.CommandLine.Tests/Binding/ModelBinderTests.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -445,7 +445,7 @@ public void PropertyInfo_can_be_bound_to_option()
445445

446446
var type = typeof(ClassWithMultiLetterSetters);
447447
var binder = new ModelBinder(type);
448-
var propertyInfo = type.GetProperties().First();
448+
var propertyInfo = type.GetProperties()[0];
449449

450450
binder.BindMemberFromValue(
451451
propertyInfo,
@@ -574,9 +574,8 @@ public void Explicit_model_binder_binds_only_to_configured_ctor_parameters()
574574
var stringOption = new Option("-b") { Argument = new Argument<string>() };
575575
var parser = new Parser(intOption, stringOption);
576576
var ctor = typeof(ClassWithMultiLetterCtorParameters)
577-
.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
578-
.First();
579-
var paramInfo = ctor.GetParameters().First();
577+
.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
578+
var paramInfo = ctor.GetParameters()[0];
580579

581580
var bindingContext = new BindingContext(parser.Parse("-a 42 -b Hello"));
582581
var binder = new ModelBinder<ClassWithMultiLetterCtorParameters>

src/System.CommandLine.Tests/Binding/ModelBindingCommandHandlerTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ public async Task Handler_method_receives_command_arguments_explicitly_bound_to_
467467
var captureMethod = GetType()
468468
.GetMethod(nameof(CaptureMethod), BindingFlags.NonPublic | BindingFlags.Static)
469469
.MakeGenericMethod(c.ParameterType);
470-
var parameter = captureMethod.GetParameters().First();
470+
var parameter = captureMethod.GetParameters()[0];
471471

472472
var handler = CommandHandler.Create(captureMethod);
473473

@@ -524,7 +524,7 @@ public async Task Handler_method_receive_option_arguments_explicitly_bound_to_th
524524
var captureMethod = GetType()
525525
.GetMethod(nameof(CaptureMethod), BindingFlags.NonPublic | BindingFlags.Static)
526526
.MakeGenericMethod(c.ParameterType);
527-
var parameter = captureMethod.GetParameters().First();
527+
var parameter = captureMethod.GetParameters()[0];
528528

529529
var handler = CommandHandler.Create(captureMethod);
530530

0 commit comments

Comments
 (0)