Repository navigation
Description
Background and motivation
System.CommandLine.Command currently requires every subcommand subtree to be instantiated up front and added to Command.Subcommands before Command.Parse(...) runs. Constructing a Command in a large CLI typically allocates all of its Option<T> and Argument<T> symbols, nested subcommands, validators, action/completion delegates, and localized .resx Description / HelpName strings—even though CommandLineParser.Tokenize only reads direct child Name and Aliases strings when building ValidTokens(), and ParseOperation never visits unmatched sibling subtrees during parsing, validation, or subcommand --help.
dotnet/command-line-api#1956 previously requested lazy subcommand initialization and was closed pending profiling from a real-world application because the synthetic startup benchmark had no subcommands and no localized strings.
We prototyped this proposal end-to-end in dotnet/command-line-api and dotnet/sdk (dotnet, dotnet-aot, and dotnet-watch), replacing eager top-level subcommand construction and removing dotnet/sdk#56267's two-token <command> --help workaround. In dotnet, DotNetCommandDefinition and Parser define 32 top-level commands, nested subtrees (11 under workload, 8 under tool, 4 under solution), hundreds of options and arguments, localized .resx strings, and Template Engine / NuGet command wiring.
Prototype measurements (dotnet/sdk, Windows x64 Release ReadyToRun)
-
Exact thread-allocated bytes (
GC.GetAllocatedBytesForCurrentThread, warm JIT):Parser.CreateCommand()alone drops from427,952 Bto14,688 B(-96.6%,29.1xsmaller).- Full
CreateCommand() + Parse(...) + IsDotnetBuiltInCommand():dotnet --version:440,600 B->27,752 B(-93.7%)dotnet externalcheck --help(externaldotnet-*tool dispatch):441,480 B->28,520 B(-93.5%)dotnet sln list:445,528 B->37,080 B(-91.7%)dotnet build app.csproj -c Release:456,664 B->73,472 B(-83.9%)
dotnet-watch(CommandLineOptions.Parse(["--quiet", "run", "-c", "Release"])):453,464 B->68,416 B(-84.9%).
-
Cold-process EventPipe
gc-verboseallocation traces & 30-sample interleaved wall-clock latency (comparing pre-dotnet/sdk#56267 eager baseline, dotnet/sdk#56267's 2-token<command> --helpworkaround, and theSystem.CommandLinelazy prototype):CLI Invocation Baseline Program.MainBdotnet/sdk#56267 Workaround Program.MainBPrototype Program.MainB (vs. Baseline)Baseline Median ms dotnet/sdk#56267 Median ms Prototype Median ms (vs. Baseline) dotnet --version745,552637,040106,088(-85.8%)230.8230.2208.7(-22.1 ms,-9.6%)dotnet build --help745,320212,176212,176(-71.5%)251.6229.9234.0(-17.6 ms,-7.0%)dotnet build --help --no-restore753,496753,520212,176(-71.8%)251.8251.7235.0(-16.8 ms,-6.7%)dotnet sln list --help745,296637,040106,088(-85.8%)250.7251.3232.1(-18.7 ms,-7.4%)dotnet sln list(command execution)745,320744,392106,088(-85.8%)249.3248.6229.0(-20.3 ms,-8.1%)dotnet reference --help— — — 308.1285.0288.8(-19.2 ms,-6.2%)dotnet externalcheck --help755,808743,152212,176(-71.9%)294.5293.3271.9(-22.5 ms,-7.6%)(Full-process sampled allocations drop by
38.2%–45.8%, from~1.40 MBto755–862 KB, where~545 KBis fixedNativeRuntimeEventSourcetracing overhead. NativeAOTdotnet-aotbinary size changes by+0.08%, and all 54/54 Managed + NativeAOT output parity scenarios and 3,200+System.CommandLine/dotnet/dotnet-aot/dotnet-watchtests pass with zero regressions.)
Without support in System.CommandLine, dotnet/sdk#56267 could only optimize exact two-token dotnet <command> <help-option> invocations by constructing a separate minimal RootCommand. As the table shows, that workaround leaves ordinary invocations (dotnet --version, dotnet sln list, external tools, dotnet-watch, and multi-token help) paying the full 32-command cost, breaks ReferenceEquals(cmd, Parser.RootCommand) and global option lookups (DiagOption, CliSchemaOption), and requires duplicate command/alias switches that caused parity regressions during review (dotnet/sdk#57103).
First-class lazy subcommand registration on Command lets ValidTokens() route on (name, aliases) without instantiating unselected subcommands, while keeping a single canonical RootCommand tree across managed, NativeAOT, and nested subcommand paths.
(Related upstream issues: directly addresses dotnet/command-line-api#1956 and avoids eager .resx lookups on unselected subtrees noted in dotnet/command-line-api#1008 and dotnet/command-line-api#1915. HelpBuilder invoking CompletionSources when HelpName is unset—dotnet/command-line-api#1584 / dotnet/command-line-api#2035—is intentionally kept separate from this proposal.)
API Proposal
namespace System.CommandLine;
public partial class Command
{
public void AddSubcommand(string name, Func<Command> subcommandFactory);
public void AddSubcommand(string name, ReadOnlySpan<string> aliases, Func<Command> subcommandFactory);
public bool ContainsSubcommand(string nameOrAlias);
public bool ContainsSubcommand(string nameOrAlias, StringComparison comparisonType);
public bool TryGetSubcommand(string nameOrAlias, [NotNullWhen(true)] out Command? subcommand);
public bool TryGetSubcommand(string nameOrAlias, StringComparison comparisonType, [NotNullWhen(true)] out Command? subcommand);
}Behavioral specification
- Registration (
AddSubcommand):- Validates
nameand each element ofaliasesusing existingSymbolnon-null / non-empty / non-whitespace rules (ArgumentNullException/ArgumentException) and throwsArgumentNullExceptionwhensubcommandFactoryisnull. - Appends a deferred subcommand entry to
Subcommandsat the current index without invokingsubcommandFactory.
- Validates
- Tokenization, parsing, and string-based result lookup:
ValidTokens()registers each deferred entry'snameandaliases(StringComparison.Ordinal, matchingAliasSetand eagerCommandtokenization) without invokingsubcommandFactory.- When
Tokenizematches a token to a deferred subcommand entry, only that entry is materialized, attached tothisas parent (AddParent), and used to tokenize and parse remaining tokens. Unmatched sibling entries and nested deferred subcommands remain unmaterialized. ParseResult.GetResult(string)/GetValue<T>(string)(SymbolResultTree.GetResult(string)) indexes symbols along the parsedCommandResultchain first (falling back to full-tree indexing only whennameis absent from all parsed commands), so string-based lookups on parsed commands do not materialize sibling subcommands while preserving existingArgumentExceptionbehavior on unknown names.
- Materialization invariants and thread safety:
- Each deferred entry is materialized at most once using
LazyThreadSafetyMode.ExecutionAndPublication, preserving thread-safe concurrentCommand.Parse(...)calls on a shared staticRootCommand. - Materialization throws
InvalidOperationExceptionifsubcommandFactoryreturnsnull, returns aCommandwhoseNamedoes not equalname(StringComparison.Ordinal), returns aCommandwhoseAliasescontain an alias not declared inaliases, or re-enters itself recursively. - Any declared
aliasesnot yet present on the returnedCommand.Aliasesare added automatically before publication, so inline factories do not need to repeat aliases while mismatches cannot silently drift.
- Each deferred entry is materialized at most once using
Subcommands(IList<Command>) andChildrensemantics:Subcommands.Countincludes both eager and deferred entries without materializing.Subcommands[index](getter),Subcommands.GetEnumerator(),Children, andSubcommands.CopyTomaterialize accessed deferred entries on demand in registration order. Parent-level help (dotnet workload --help) and parent-level completions (dotnet <TAB>) therefore materialize only direct children of that parent, leaving sibling trees and lazy grandchildren unmaterialized.Subcommands[index] = value,Subcommands.RemoveAt(index), andSubcommands.Clear()mutate slots (detachingParenton already-materialized entries) without invoking unmaterialized factories.Contains(Command),IndexOf(Command), andRemove(Command)inspect materialized entries without forcing uninvoked factories.
- Non-enumerating lookup (
ContainsSubcommand/TryGetSubcommand):- Throws
ArgumentNullExceptionifnameOrAliasisnullandArgumentExceptionifcomparisonTypeis not a validStringComparison. Overloads withoutcomparisonTypedefault toStringComparison.Ordinal. ContainsSubcommandchecks direct eager and deferred subcommand names and aliases without materializing any deferred entry.TryGetSubcommandlocates a direct subcommand by name or alias, materializes only that entry if deferred, and returnsfalsewithout materializing anything when unmatched. (Case-insensitive overloads support hosts such asdotneton Windows/macOS that parse ordinally but checkStringComparison.OrdinalIgnoreCaseso built-in command names take precedence over externaldotnet-*executables onPATH.)
- Throws
API Usage
1. Multi-command CLI with aliases and nested lazy subcommands
using System.CommandLine;
RootCommand root = new("dotnet");
root.AddSubcommand("build", static () => CreateBuildCommand());
root.AddSubcommand("solution", ["sln"], static () =>
{
Command solution = new("solution", "Modify solution files");
solution.AddSubcommand("list", static () => CreateSolutionListCommand());
solution.AddSubcommand("add", static () => CreateSolutionAddCommand());
return solution;
});
// Tokenizes "sln" -> materializes only "solution", then "list" -> materializes only "list".
// "build" and "solution add" are never allocated.
ParseResult result = root.Parse(["sln", "list"]);
return result.Invoke();2. Shared command definitions layered with host-specific configuration (dotnet, dotnet-aot, dotnet-watch)
internal sealed class DotNetCommandDefinition : RootCommand
{
private readonly Func<Command, Command>? _configureSubcommand;
public DotNetCommandDefinition(Func<Command, Command>? configureSubcommand = null)
: base("dotnet")
{
_configureSubcommand = configureSubcommand;
Add(DiagOption);
Add(VersionOption);
RegisterSubcommand("build", static () => new BuildCommandDefinition());
RegisterSubcommand("new", static () => new NewCommandDefinition());
RegisterSubcommand("solution", ["sln"], static () => new SolutionCommandDefinition());
// ... remaining top-level commands
}
private void RegisterSubcommand(string name, Func<Command> factory) =>
AddSubcommand(name, _configureSubcommand is null ? factory : () => _configureSubcommand(factory()));
private void RegisterSubcommand(string name, ReadOnlySpan<string> aliases, Func<Command> factory) =>
AddSubcommand(name, aliases, _configureSubcommand is null ? factory : () => _configureSubcommand(factory()));
}
// Managed CLI wires handlers, completions, or replacement commands (e.g., `dotnet new`)
// only for the command actually matched during Parse:
RootCommand root = new DotNetCommandDefinition(ConfigureManagedSubcommand);
// Non-enumerating case-insensitive check for built-in vs. external `dotnet-*` tool dispatch:
if (root.TryGetSubcommand(candidateName, StringComparison.OrdinalIgnoreCase, out Command? builtIn))
{
// Materializes at most `candidateName`; external tools materialize zero subcommands.
}Alternative Designs
-
Command.Add(...)overloads instead ofAddSubcommand(...):public void Add(string name, Func<Command> subcommandFactory); public void Add(string name, ReadOnlySpan<string> aliases, Func<Command> subcommandFactory);
CommandimplementsIEnumerableand exposesAdd(Argument),Add(Option), andAdd(Command)for C# collection initializers (new RootCommand { { "build", CreateBuildCommand } }).AddSubcommandwas chosen as the primary name because existingAddoverloads disambiguate child symbol kind by parameter type (Argumentvs.Optionvs.Command), whereascmd.Add("build", Create)with a method group hidesCommandat the call site. Either naming (or both, withAddforwarding toAddSubcommand) works with the same underlying model. -
Command.Add(Lazy<Command>):
Rejected becauseLazy<Command>does not exposeNameorAliaseswithout evaluatingLazy<Command>.Value.ValidTokens()would have to materialize everyLazy<Command>on the first token of every parse, defeating lazy initialization. -
LazyCommand : Commandwrapper orprotected virtual void Initialize():
Rejected for three reasons:- Subclass field initializers (such as
public readonly Option<string> FrameworkOption = new(...)across SDK*CommandDefinitiontypes) execute whennew TCommand()runs, before any virtualInitialize()hook can defer them. - A wrapper
Commandbreaks runtime type checks againstCommandResult.Command(for example,command is ICustomHelporcommand is MSBuildCommandDefinition). - Host layers that replace a command definition with a derived or composite
Commandinstance (such asNewCommandFactory.Create(...)indotnet new) require aFunc<Command>factory rather than in-place mutation.
- Subclass field initializers (such as
-
Accepting
string? descriptionandbool hiddeninAddSubcommand:
Rejected because passingdescription: Resources.MyCommandDescriptionat registration time re-introduces eager.resxResourceManagerlookups on every invocation (dotnet/command-line-api#1008) and duplicates metadata that can drift from the constructedCommand. Parent--helpand parent-level completions are infrequent interactive operations where materializing only direct children of that parent (without materializing sibling trees or lazy grandchildren) is already bounded. -
IEnumerable<string>alias overloads:
ReadOnlySpan<string>accepts C# collection expressions (["sln"]),string[](via implicit conversion), and slices across both modern.NETandnetstandard2.0(System.CommandLinealready referencesSystem.Memoryonnetstandard2.0), avoiding array allocations when empty or stack-backed.
Risks
- Deferred factory failures: Invalid
Commandconstruction or aName/alias mismatch insidesubcommandFactorythrowsInvalidOperationExceptionwhen that subcommand is first materialized rather than duringRootCommandconstruction. StrictNameandAliasesvalidation on materialization ensures mismatches fail deterministically in command help, schema, or parser tests instead of silently misrouting tokens. - Unintended full enumeration via LINQ or missing string-based option lookups: Existing code calling
command.Subcommands.FirstOrDefault(...)remains source- and binary-compatible (IList<Command>is unchanged), but enumeratingSubcommandsmaterializes entries as visited. Similarly, callingParseResult.GetResult(string)with an option name that does not exist anywhere along the parsedCommandResultchain must still scan unparsed subtrees to preserve its existingnullvs.ArgumentExceptioncontract (prototyping indotnet/sdkcaught bothParser.GetBuiltInCommandandResultNavigationExtensions.SafelyGetValueForOption(string)doing this).ContainsSubcommand,TryGetSubcommand, andCommandResult.Children/ typedOption<T>lookups provide explicit non-enumerating paths for startup-critical callers. - NativeAOT / trimming: The API uses explicit
Func<Command>delegates with no reflection or dynamic code generation, preservingIsAotCompatibleandIsTrimmableacrossSystem.CommandLine(+0.08%binary delta ondotnet-aot).
Activity
dotnet-policy-service commentedon Nov 13, 2026
Tagging subscribers to this area: @dotnet/area-system-console
See info in area-owners.md if you want to be subscribed.
JeremyKuhne commentedon Nov 13, 2026
@baronfel
JeremyKuhne commentedon Nov 13, 2026
Additional Measurements: Commands Staying Entirely in NativeAOT (
dotnet-aot)We also measured commands handled end-to-end inside
dotnet-aotwithout falling back to the managed CLI (--version,sdk check,sln list,build --help, andsln list --help).Heap allocations inside
CLI_AOT(GC.GetAllocatedBytesForCurrentThread)Because
Parser.ConfigureAotActionspreviously iteratedrootCommand.Subcommandsand walked every subtree (SetAotFallbackRecursively), lazy subcommands cutCLI_AOTheap allocations by 68%–93% (~358–384 KBsaved per invocation):Parser.CreateCommand()CreateCommand + ParseCreate + Parse + Invokedotnet --version399,384 B->14,704 B408,864 B->24,624 B411,632 B->27,392 B-93.3%(-384 KB)dotnet sln list399,384 B->14,704 B413,440 B->34,296 B433,184 B->54,040 B-87.5%(-379 KB)dotnet sln list --help399,384 B->14,704 B413,744 B->34,608 B434,504 B->55,176 B-87.3%(-379 KB)dotnet build --help399,384 B->14,704 B424,016 B->66,000 B496,992 B->138,888 B-72.1%(-358 KB)dotnet sdk check399,384 B->14,704 B411,160 B->27,720 B564,712 B->181,192 B-67.9%(-384 KB)(
CreateCommand()alone drops-96.3%(27.2x), from399,384 Bto14,704 B.)Unlike Managed ReadyToRun (which saves 17–22.5 ms), wall-clock time for commands that stay in NativeAOT is flat within
~1 msmeasurement noise (~78–80 msend-to-end process,~41–43 msinsidedotnet_execute):~230–308 ms): Eagerly instantiating all 32 command definitions andConfigureManagedActionstriggers assembly loads, type-loader/R2R fixups, and Tier-0 JIT acrossMicrosoft.TemplateEngine.*,NuGet.CommandLine.XPlat, and.resxresources—costing~17–22.5 msof CPU time.~78–80 msprocess,~41–43 msindotnet_execute): Every definition is already native x64 code in a single image (zero assembly load, zero type loader, zero JIT, and Template Engine / NuGet XPlat are excluded underCLI_AOT). Bump-allocating~380 KBin Gen0 without triggering a GC takes< 1 msin native code, while the~41 msinsidedotnet_executeis dominated byTelemetryClient/ OTel startup inNativeEntryPoint.cs.JeremyKuhne commentedon Nov 19, 2026
@KathleenDollard @jonsequitur If you have any feedback it would be greatly appreciated :)
adamsitnik commentedon Nov 20, 2026
Hi @JeremyKuhne
Thank you for your proposal. I totally see the benefits for dotnet/sdk, but at the same time I believe it's one of very few of our customers who have such large symbol trees. I am not against it, it just seems to be quite niche.
Why would you like to expose those APIs? I am just wondering if we should add a possibility to add lazy symbols and make parser aware of them and use similar methods internally or also expose them.
In the past, Command was exposing following methods:
We have removed them in #1989 in order to comply with the BCL API guidelines (#1987). The idea was simple: if we expose a collection, users can add, remove, iterate and whatever else they need:
All of them expose
IList, because we need to set the parent when they are being added:command-line-api/src/System.CommandLine/ChildSymbolList{T}.cs
Lines 37 to 41 in 1b0c04a
I know that this would be also a breaking change, but I wonder, if we could just expose the internal
ChildSymbolListtype instead ofIListand extend it with the ability to add lazy symbol registrations.Then just make all its methods (indexer, enumeration etc) materialize the symbols when requested via public API, but also expose some internal APIs that would allow the parser to avoid creating them if possible.
Then all the public APIs should just work:
command-line-api/src/System.CommandLine/Command.cs
Lines 44 to 57 in 1b0c04a
This would of course be a breaking change, but 99.99% of users would not encounter any compilation or runtime errors because the type would still implement
IList.adamsitnik commentedon Nov 20, 2026
This is what I got: #2895
JeremyKuhne commentedon Nov 21, 2026
Thanks @adamsitnik! I've dug into this more and I propose narrowing the API in response to your comments: add lazy registration, keep lookup inside the parser, and preserve the existing
IList<Command>getter to retain binary compatibility.Your collection suggestion supplies the useful mechanism: store registration metadata and materialize real commands when needed. It does not require exposing that collection.
New proposed surface
Only the two
Addoverloads are new.An internal compact collection stores eager commands or deferred registrations containing a name, owned aliases, and factory/publication state. Registration validates its inputs and copies caller-mutable alias storage without invoking the factory. Parsing uses the metadata and constructs only the selected real command. The result must be non-null, match the registered name, and introduce no undeclared aliases; validation and parent attachment precede publication. Concurrent first use shares one command or cached failure; same-factory reentry is rejected.
Countdoes not materialize commands. Indexing and enumeration materialize visited entries, so help and completion can obtain command metadata.Contains,IndexOf, andRemoveinspect eager or published entries without running uncreated factories. Known unselected direct-child result lookup returnsnullwithout sibling construction; unknown-name lookup retains the existing compatibility fallback.The updated proposal reduces managed GC allocations in my tests by 69-83% and AOT by 51-62%.