autofac/Autofac

Performance & Memory Issue on container setup

已關閉

#1,446 建立於 2025年2月13日

 (5 則留言) (0 個反應) (0 位負責人)C# (827 個分叉)batch import
enhancementhelp wanted

倉庫指標

星標
 (4,327 顆星)
PR 合併指標
 (平均合併 3小時 24分鐘) (30 天內合併 10 個 PR)

描述

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

貢獻者指南