pakrym / jab

C# Source Generator based dependency injection container implementation.
MIT License
1.03k stars 33 forks source link

Performance Improvements Suggestion: Removing the `TryAddDisposable()` #170

Open rafaelsc opened 7 months ago

rafaelsc commented 7 months ago

Currently, Jab uses runtime checks to check if the newly created instance is a IDisposable or IAsyncDisposable, this could be done by the Jab in compile time improving the runtime performance.

So instead of this code to all new instances:

Jab.Performance.Basic.Transient.ITransient1 IServiceProvider<Jab.Performance.Basic.Transient.ITransient1>.GetService()
{
    Jab.Performance.Basic.Transient.Transient1 service = new Jab.Performance.Basic.Transient.Transient1();
    TryAddDisposable(service);
    return service;
}

private global::System.Collections.Generic.List<object>? _disposables;
private void TryAddDisposable(object? value)
{
    if (value is global::System.IDisposable || value is System.IAsyncDisposable)
        lock (this)
        {
            (_disposables ??= new global::System.Collections.Generic.List<object>()).Add(value);
        }
}

Update to this code only for new instances from IDisposable or IAsyncDisposable.

Jab.Performance.Basic.Transient.ITransient1 IServiceProvider<Jab.Performance.Basic.Transient.ITransient1>.GetService()
{
    Jab.Performance.Basic.Transient.Transient1 service = new Jab.Performance.Basic.Transient.Transient1();
    _disposables.Add(value);
    return service;
}

private global::System.Collections.Concurrent.ConcurrentBag<IDisposable> _disposables = [];

and similar changes for IAsyncDisposable.

See: https://github.com/pakrym/jab/pull/168#discussion_r1465940230