← Back to all articles

More Reactive Extensions Performance Improvements

I blogged about performance when Rx was officially released a few months ago.

Last week the team released a new version (1.1.11111) where “The major focus of this release is performance-related work”.

Subject<T> now uses non-blocking synchronization!

Internally a subject has a list of subscribed observers. Traditionally, concurrent access to the list has been synchronised internally with a C# lock (Monitor). The latest release uses compare & swap (CAS) operation to modify it’s internal state. As OnNext doesn’t modify the internal state it doesn’t even need a CAS operation, it simply dispatches the notifications to all the observers.

Test code (from Rx team)

for (int n = 0; n < 10; n++)
{
    var c = new CountdownEvent(n);

    var s = new Subject();
    for (int i = 0; i < n; i++)
        s.Subscribe(_ => { }, () => c.Signal());

    var sw = Stopwatch.StartNew();

    Scheduler.ThreadPool.Schedule(() =>
    {
        for (int i = 0; i < 100000000; i++)
            s.OnNext(42);
        s.OnCompleted();
    });

    c.Wait();
    sw.Stop();
    Console.WriteLine(sw.Elapsed);
}

Results

image

Comments