autofac/Autofac

Performance & Memory Issue on container setup

クローズ

#1,446 opened on 2025/02/13

 (5 件のコメント) (0 件のリアクション) (0 人の担当者)C# (827 件のフォーク)batch import
enhancementhelp wanted

Repository metrics

Stars
 (4,327 個のスター)
PR merge metrics
 (平均マージ 3h 24m) (30d で 10 merged PRs)

説明

Describe the Bug

In the Configure method of the Module class (https://github.com/autofac/Autofac/blob/develop/src/Autofac/Module.cs#L53), event handlers are always created for the events ‘componentRegistry.RegistrationSourceAdded’ & ‘componentRegistry.Registered’. However, if the feature is not required at all, this leads to poor performance when setting up the container with a large number of modules. It also leads to high memory consumption.

Steps to Reproduce

I've created a Benchmark to reproduce this

public class SetupContainerBenchmark
{
    private IContainer _container;

    [Benchmark]
    public void SetupContainerWith10000Modules()
    {
        var builder = new ContainerBuilder();
        for (var i = 0; i < 10000; i++)
        {
            builder.RegisterModule<SimpleModule>();
        }

        _container = builder.Build();
    }
}
internal class SimpleModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        base.Load(builder);

        builder.RegisterType<SampleType>().AsSelf();
    }
}
internal class SampleType;

BenchmarkDotNet v0.14.0, Windows 11 (10.0.26100.2894) 12th Gen Intel Core i9-12900HK, 1 CPU, 20 logical and 14 physical cores .NET SDK 8.0.405 [Host] : .NET 8.0.12 (8.0.1224.60305), X64 RyuJIT AVX2 [AttachedDebugger] DefaultJob : .NET 8.0.12 (8.0.1224.60305), X64 RyuJIT AVX2

Origin Result:

Method Mean Error StdDev Gen0 Gen1 Allocated
SetupContainerWith10000Modules 1.594 s 0.0476 s 0.1403 s 133000.0000 24000.0000 1.56 GB

If i remove the Event Registration:

Method Mean Error StdDev Gen0 Gen1 Gen2 Allocated
SetupContainerWith10000Modules 73.26 ms 1.942 ms 5.509 ms 5250.0000 2375.0000 750.0000 55.32 MB

Expected Behavior

It would be useful if you could prevent the Event Registration if not needed, to increase the container setup performance and to decrease the memoery usage

Dependency Versions

Autofac: 8.2

コントリビューターガイド