Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Performance of CBORObject ByteString Decoding #90

Open
safestak-keith opened this issue Jul 18, 2022 · 0 comments
Open

Improve Performance of CBORObject ByteString Decoding #90

safestak-keith opened this issue Jul 18, 2022 · 0 comments
Assignees

Comments

@safestak-keith
Copy link
Collaborator

Currently ByteString type CBORObjects are decoded to byte[] using the long form expression

var byteArray = ((string)cborObject.DecodeValueByCborType()).HexToByteArray();

Where DecodeValueByCborType() exists in CBORExtensions.cs as

public static object DecodeValueByCborType(this CBORObject cborObject)
{
    object result = new object();
    switch (cborObject.Type)
    {
      case CBORType.ByteString:
          result = cborObject.ToString().Replace("h", "").Replace("'", "");
          break;
    }
}

This approach is found in hot paths for Transaction CBOR deserialization:
image

For the CardanoSharp.Wallet SDK to be used in performance-oriented applications we should use the simpler form which doesn't incur additional computation or allocation overhead yet returns same result.

var byteArray = cborObject.GetByteString();

Test to validate equivalence of the approaches

  [Fact]
  public void GetByteStringEquivalence()
  {
      var bytes = new byte[]
          {
             0x01, 0x01, 0x06, 0x00, 0x00, 0x00, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
             0x00, 0x0b, 0x82, 0x01, 0xfc, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
          };
      var cborBytestring = CBORObject.FromObject(bytes);
      var decodedFromStringHex = ((string)cborBytestring.DecodeValueByCborType()).HexToByteArray();
      var decodedByteString = cborBytestring.GetByteString();
      Assert.Equal(decodedFromStringHex.Length, decodedByteString.Length);
      for (int i = 0; i < bytes.Length; i++)
      {
          Assert.Equal(bytes[i], decodedFromStringHex[i]);
          Assert.Equal(bytes[i], decodedByteString[i]);
      }
  }
@safestak-keith safestak-keith self-assigned this Jul 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant