1brc icon indicating copy to clipboard operation
1brc copied to clipboard

Implement ISpanFormattable on Summary

Open sonnemaf opened this issue 2 years ago • 5 comments

Hi,

I think you can win something by implementing ISpanFormattable on Summary. This will make the string interpolation in Console.Write($"{pair.Name}={pair.Value}") run faster. You avoid the ToString() method.

You can try this using this code. It was faster on my (slow) computer.

public struct Summary : ISpanFormattable {

    public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) {
        return destination.TryWrite($"{Min / 10.0:N1}/{Average / 10.0:N1}/{Max / 10.0:N1}", out charsWritten);
    }

    public string ToString(string? format, IFormatProvider? formatProvider) {
        return ToString();
    }

If it works you can even gain more performance by reimplementing the TryFormat method without the use of the TryWrite extensionmethod. It quite a lot of work but might work.

Regards,

Fons

sonnemaf avatar Jan 09 '24 20:01 sonnemaf

Oh, do you realize that if everything other than ProcessChunk was exactly zero then the difference would be less than the noise on my very stable dedicated benchmarking machine!?

buybackoff avatar Jan 09 '24 20:01 buybackoff

Are you saying that the Console.Write() is free? Can't imagine that.

sonnemaf avatar Jan 09 '24 20:01 sonnemaf

It takes ~ 15-20 msec. Well, my benchmark resolution is better than that, I will admit that. Will see if the impact is visible.

buybackoff avatar Jan 09 '24 20:01 buybackoff

Actually I already use that locally, not committed yet. I thought you've implemented Utf8 formatting to a Span<byte>.

image

buybackoff avatar Jan 09 '24 20:01 buybackoff

I actually like this because it's the right approach. Even if there is not difference in performance. Thank you!

image

image

buybackoff avatar Jan 09 '24 21:01 buybackoff