Skip to content

Possible lock(System.Threading.Lock) perf improvement #115226

@peto268

Description

@peto268

Reading https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-9/#threading i'm wondering if instead of replacing lock(_lock) with _lock.EnterScope() ... Dispose the compiler shouldn't actually use something like:

_lock.Enter();
try
{
    ...
}
finally
{
    _lock.Exit();
}

This prevents the allocation of the scope struct and in my benchmarks:

[Benchmark]
public void WithLock()
{
    lock (_lock)
    {
        _value++;
    }
}

[Benchmark]
public void WithLock2()
{
    _lock2.Enter();
    try
    {
        _value++;
    }
    finally
    {
        _lock2.Exit();
    }
}

this performs ~5% better.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.ThreadingquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions