Skip to content

[API Proposal]: Add IConfiguration.HasChildren #83692

Closed as not planned
Closed as not planned

Description

@layomia

Background and motivation

We should add a new HasChildren property to IConfiguration. An implementation given existing APIs might look like this:

public static bool HasChildren(IConfiguration configuration)
{
    foreach (IConfigurationSection section in configuration.GetChildren())
    {
        return true;
    }
    return false;
}

This implementation makes allocations which is not ideal. We could get better perf with a new API with a more optimal framework implementation.

API Proposal

namespace Microsoft.Extensions.Configuration
{
    public interface IConfiguration
    {
+        public bool HasChildren { get; }
    }
}

API Usage

A primary user of this feature would be the configuration binding source generator. Sample code it would generate:

private static void BindCore(IConfiguration configuration, MyClass obj)
{
    ThrowIfNull(obj);

    if (configuration["MyString"] is string stringValue0)
    {
        obj.MyString = stringValue0;
    }

    IConfigurationSection section2 = configuration.GetSection("MyList");
    if (section2.HasChildren)
    {
        List<int> temp3 = obj.MyList;
        temp3 ??= new List<int>();
        BindCore(section2, ref temp3);
        obj.MyList = temp3;
    }

    IConfigurationSection section4 = configuration.GetSection("MyDictionary");
    if (section4.HasChildren)
    {
        Dictionary<string, string> temp5 = obj.MyDictionary;
        temp5 ??= new Dictionary<string, string>();
        BindCore(section4, ref temp5);
        obj.MyDictionary = temp5;
    }

    // Repeat for every object or collection property on MyClass
  }

We see that the binding performance would improve with a more optimal implementation, particularly for large object graphs.

cc @tarekgh @eerhardt @davidfowl @dotnet/area-extensions-configuration

Activity

  1. added
    api-suggestionEarly API idea and discussion, it is NOT ready for implementation
    on Mar 20, 2023
  2. added this to the 8.0.0 milestone on Mar 20, 2023
  3. self-assigned this
    on Mar 20, 2023
  4. tarekgh commented on Mar 20, 2023

    @tarekgh
    Member

    I think this needs to be an extension method on the IConfiguration and not extending the original interface. Right? Can't we just add this to the internal extensions we have here https://source.dot.net/#Microsoft.Extensions.Configuration/InternalConfigurationRootExtensions.cs,13? I know we need to have a public way to access it though.

  5. layomia commented on Mar 20, 2023

    @layomia
    ContributorAuthor

    I think this needs to be an extension method on the IConfiguration and not extending the original interface.

    I know we need to have a public way to access it though.

    Would we be establishing a new pattern for APIs on the type?

    Having it be a property on the type itself seemed natural to me since we expect this to be a cheap/cached check. I did a quick scan of what an implementation would look like to verify this assumption, but I'll have to dive a bit deeper to be sure.

    We could also consider optimizing GetChildren(); there's a lot of LINQ usage in the implementation.

  6. eerhardt commented on Mar 20, 2023

    @eerhardt
    Member

    In order for this to actually be beneficial, it would need to be a property on the interface. An extension property could only hard-code our own configuration types - ConfigurationRoot, ConfigurationManager, etc. For other IConfiguration types, it would need to call GetChildren().Any().

    We could also consider optimizing GetChildren(); there's a lot of LINQ usage in the implementation.

    Note that in this case we are eagerly building the full list (which we need to do for the reason in the comment):

    // Eagerly evaluate the IEnumerable before releasing the reference so we don't allow iteration over disposed providers.
    return children.ToList();

  7. tarekgh commented on Mar 20, 2023

    @tarekgh
    Member

    it would need to be a property on the interface.

    Is it possible we can extend this interface? note this interface is supported on the .NET Framework which adding anything there will be a breaking change.

  8. eerhardt commented on Mar 20, 2023

    @eerhardt
    Member

    We would either do it the way we IMemoryCache.GetCurrentStatistics:

    #if NET6_0_OR_GREATER
    /// <summary>
    /// Gets a snapshot of the cache statistics if available.
    /// </summary>
    /// <returns>An instance of <see cref="MemoryCacheStatistics"/> containing a snapshot of the cache statistics.</returns>
    MemoryCacheStatistics? GetCurrentStatistics() => null;
    #endif

    Or we could introduce a new interface that had the new property on it. Then an extension method could check for the interface and cast to it. And if the IConfiguration didn't implement the interface, it could fall back to GetChildren().Any(). That would still work on .NET Framework.

  9. davidfowl commented on Mar 21, 2023

    @davidfowl
    Member

    Help me understand the case this is optimized for? For a missing section the IConfigurationSection.Value is null, so

    public static bool Exists([NotNullWhen(true)] this IConfigurationSection? section)
    would work right? If there is a section then we're going to enumerating it anyways.

  10. layomia commented on Mar 21, 2023

    @layomia
    ContributorAuthor

    I wasn't aware of that implementation. I also used section.GetChildren().Any() initially but the feedback is that we want to avoid LINQ in the source gen implementation.

    If there is a section then we're going to enumerating it anyways.

    I guess it would be helpful in the cases where there are no children so we avoid allocating a section.

  11. davidfowl commented on Mar 22, 2023

    @davidfowl
    Member

    I wasn't aware of that implementation. I also used section.GetChildren().Any() initially but the feedback is that we want to avoid LINQ in the source gen implementation.

    We should use Exists in the source generator.

    I guess it would be helpful in the cases where there are no children so we avoid allocating a section.

    It'd only be helpful in the case where there was a section, but it was empty.

    In the latter case this looks like it can be optimized to avoid allocations for empty sections.

  12. eerhardt commented on Mar 22, 2023

    @eerhardt
    Member

    In the latter case this looks like it can be optimized to avoid allocations for empty sections.

    IEnumerable<IConfigurationSection> children = providers
    .Aggregate(Enumerable.Empty<string>(),
    (seed, source) => source.GetChildKeys(seed, path))
    .Distinct(StringComparer.OrdinalIgnoreCase)
    .Select(key => root.GetSection(path == null ? key : ConfigurationPath.Combine(path, key)));
    if (reference is null)
    {
    return children;
    }
    else
    {
    // Eagerly evaluate the IEnumerable before releasing the reference so we don't allow iteration over disposed providers.
    return children.ToList();
    }

    I'm seeing at least 4 allocations there:

    1. Aggregate
    2. Distinct
    3. Select
    4. Optionally the List being allocated
    5. Lastly the enumerator

    (There are actually more under the covers, as source.GetChildKeys(seed, path) internally creates a List<T>, and so does Select.)

    Here's a benchmark using 7.0.0:

    [MemoryDiagnoser]
    public class ConfigurationSectionBenchmarks
    {
        private readonly ConfigurationManager config;
        private readonly IConfigurationSection section;
    
        public ConfigurationSectionBenchmarks()
        {
            config = new ConfigurationManager();
            section = config.GetSection("NotExist");
        }
    
        [Benchmark]
        public bool Exists() => section.Exists();
    }

    And the results - almost half a KB is allocated every time you call Exists() on an empty section:

    Method Mean Error StdDev Gen0 Allocated
    Exists 232.6 ns 3.80 ns 3.55 ns 0.0765 480 B

    It'd only be helpful in the case where there was a section

    Note that there is always a section returned, even if it doesn't exist in the configuration:

    public IConfigurationSection GetSection(string key) => new ConfigurationSection(this, key);

    We will create an IConfigurationSection for each property in the object, whether that property has anything in the configuration or not. (Note the other implementations of GetSection are the same.)

    , but it was empty.

    This would also help in the case where there is information in the configuration. Calling GetChildren().Any() just to check if there are any, and then calling GetChildren() again to actually enumerate them throws away the information built up above (the Aggregate, Distinct, Select, and most importantly the ToList() at the end).

  13. davidfowl commented on Mar 23, 2023

    @davidfowl
    Member

    Optimizing for an empty section seems like an edge case? What’s motivating that?

  14. eerhardt commented on Mar 23, 2023

    @eerhardt
    Member

    Optimizing for an empty section seems like an edge case?

    1. It is optimizing for both empty and non-empty. When it is non-empty we are throwing the info away.
    2. It isn't really an edge case. Not every property in the object is always filled out in Configuration. For every property in the Type we will get a IConfigurationSection and then call GetChildren().Any() on it, whether it has a value in the configuration or not. So unless every property of the Options object has a value in the configuration, it isn't an edge case.
  15. davidfowl commented on Mar 23, 2023

    @davidfowl
    Member

    When it is non-empty we are throwing the info away.

    What do you mean?

    For every property in the Type we will get a IConfigurationSection and then call GetChildren().Any() on it, whether it has a value in the configuration or not. So unless every property of the Options object has a value in the configuration, it isn't an edge case.

    How? When there's no section we only allocate the IConfigurationSection and the Value is null. Why would we do IConfigurationSection().Any() in that scenario?

    I don't see how that code above is allocating per call to Exists on an non-existent section... (what am I missing..). Also, how does the above API avoid allocating the IConfigurationSection for every property? Doesn't the code for object binding still call GetSection(...).HasChildren?

  16. eerhardt commented on Mar 23, 2023

    @eerhardt
    Member

    When it is non-empty we are throwing the info away.

    What do you mean?

    if (config != null && config.GetChildren().Any())

    That call to GetChildren().Any() allocates all the objects I outlined above just to check if there are any, and then throws that all away. Then inside the if, it callsBindArray, which then calls GetChildren() again to enumerate them:

    foreach (IConfigurationSection section in config.GetChildren())

    When there's no section we only allocate the IConfigurationSection and the Value is null. Why would we do IConfigurationSection().Any() in that scenario?

    public static bool Exists([NotNullWhen(true)] this IConfigurationSection? section)
    {
    if (section == null)
    {
    return false;
    }
    return section.Value != null || section.GetChildren().Any();

    Notice the section.Value != null || section.GetChildren().Any(). When the Value is null, the left hand side is false and the GetChildren().Any() will be called.

    Also, how does the above API avoid allocating the IConfigurationSection for every property?

    It doesn't.

  17. davidfowl commented on Mar 23, 2023

    @davidfowl
    Member

    That call to GetChildren().Any() allocates all the objects I outlined above just to check if there are any, and then throws that all away. Then inside the if, it callsBindArray, which then calls GetChildren() again to enumerate them:

    OK I get it, when section.Value is null that isn't enough to determine that there's no children. This API is making more sense now 😄 . Sorry for the confusion.

  18. eerhardt commented on Mar 23, 2023

    @eerhardt
    Member

    FWIW, I don't necessarily see this as a "must have" API for .NET 8. Using the ConfigurationBinder source generator is going to give so much performance benefits over the reflection based ConfigurationBinder, these allocations aren't going to make that much of a difference. And I don't see ConfigurationBinder being on a "hot path" in most apps.

  19. removed their assignment
    on Mar 27, 2023
  20. modified the milestones: 8.0.0, Future on Jul 19, 2023
  21. modified the milestones: Future, 11.0.0 on Mar 4, 2026
  22. rosebyte commented on Mar 4, 2026

    @rosebyte
    Member

    Triage: we agree with @eerhardt

  23. locked and limited conversation to collaborators on Apr 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions