Azure / azure-sdk-for-net

This repository is for active development of the Azure SDK for .NET. For consumers of the SDK we recommend visiting our public developer docs at https://learn.microsoft.com/dotnet/azure/ or our versioned developer docs at https://azure.github.io/azure-sdk-for-net.
MIT License
5.47k stars 4.8k forks source link

Performance improvements to ContainerRegistryBlobClient #33614

Open annelo-msft opened 1 year ago

annelo-msft commented 1 year ago
KrzysztofCwalina commented 1 year ago

FYI, I was thinking about something like this (probably 100x faster than the current SB implementation):

    static readonly string prefixUtf16 = "sha256:";
    static readonly string nibbleToHexMap = "0123456789abcdef";
    public static bool TryFormatAsHexUtf16(byte[] bytes, scoped Span<char> utf16, out int charsWritten)
    {
        charsWritten = 0;
        if (utf16.Length < prefixUtf16.Length + (bytes.Length << 1)) return false;

        prefixUtf16.CopyTo(utf16);
        charsWritten = prefixUtf16.Length;

        for (int i = 0; i < bytes.Length; i++)
        {
            var nextByte = bytes[i];
            var high = (byte)(nextByte >> 4);
            utf16[charsWritten++] = nibbleToHexMap[high];
            var low = (byte)(nextByte & 0x0F);
            utf16[charsWritten++] = nibbleToHexMap[low];
        }

        return true;
    }

if you really need a string then this method could be called as:

    public static string BytesToString(byte[] bytes)
    {
        var length = prefixUtf16.Length + (bytes.Length << 1);
        char[] chars = new char[length];
        if (!TryFormatAsHexUtf16(bytes, chars, out var written)) throw new Exception("should not happen");
        return new string(chars);
    }
annelo-msft commented 1 year ago

Another suggestion to consider here: https://github.com/Azure/azure-sdk-for-net/pull/34940#discussion_r1140506122