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

Optimize AWSSDKUtils.ToHex() for speed and memory #3293

Open
wants to merge 7 commits into
base: v4-development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
53 changes: 41 additions & 12 deletions sdk/src/Core/Amazon.Util/AWSSDKUtils.cs
Expand Up @@ -39,6 +39,7 @@
#if NETSTANDARD
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Buffers;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably move outside the #if

#endif

namespace Amazon.Util
Expand Down Expand Up @@ -761,14 +762,36 @@ public static long ConvertTimeSpanToMilliseconds(TimeSpan timeSpan)
/// <returns>String version of the data</returns>
public static string ToHex(byte[] data, bool lowercase)
{
StringBuilder sb = new StringBuilder();

for (int i = 0; i < data.Length; i++)
#if NET8_0_OR_GREATER
if (!lowercase)
{
sb.Append(data[i].ToString(lowercase ? "x2" : "X2", CultureInfo.InvariantCulture));
return Convert.ToHexString(data);
}
#endif
char[] chars = ArrayPool<char>.Shared.Rent(data.Length * 2);

return sb.ToString();
try
{
Func<int, char> converter = lowercase ? (Func<int, char>)ToLowerHex : (Func<int, char>)ToUpperHex;

for (int i = 0; i < data.Length; i++)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity have you tried reversing the loop to elide bound checks?

Also could this be a candidate for string.Create since that would take care of the pooling already?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestions @danielmarbach ! Both were very helpful.

{
// Break apart the byte into two four-bit components and
// then convert each into their hexadecimal equivalent.
byte b = data[i];
int hiNibble = b >> 4;
int loNibble = b & 0xF;

chars[i * 2] = converter(hiNibble);
chars[i * 2 + 1] = converter(loNibble);
}

return new string(chars, 0, data.Length * 2);
}
finally
{
ArrayPool<char>.Shared.Return(chars);
}
}

/// <summary>
Expand Down Expand Up @@ -1171,7 +1194,18 @@ private static char ToUpperHex(int value)
// Maps 10-15 to the Unicode range of 'A' - 'F' (0x41 - 0x46).
return (char)(value - 10 + 'A');
}


private static char ToLowerHex(int value)
{
// Maps 0-9 to the Unicode range of '0' - '9' (0x30 - 0x39).
if (value <= 9)
{
return (char)(value + '0');
}
// Maps 10-15 to the Unicode range of 'a' - 'f' (0x61 - 0x66).
return (char)(value - 10 + 'a');
}

internal static string UrlEncodeSlash(string data)
{
if (string.IsNullOrEmpty(data))
Expand Down Expand Up @@ -1333,12 +1367,7 @@ public static void Sleep(TimeSpan ts)
/// </summary>
/// <param name="value">Bytes to convert.</param>
/// <returns>Hexadecimal string representing the byte array.</returns>
public static string BytesToHexString(byte[] value)
{
string hex = BitConverter.ToString(value);
hex = hex.Replace("-", string.Empty);
return hex;
}
public static string BytesToHexString(byte[] value) => ToHex(value, false);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure why we had both ToHex and BytesToHexString. Going with old codebase. The BytesToHexString is only called in AmazonS3ResponseHandler.cs. Since this is v4 I think we can just get rid of this method and update AmazonS3ReponseHandler.


/// <summary>
/// Convert a hex string to bytes
Expand Down
40 changes: 40 additions & 0 deletions sdk/test/NetStandard/UnitTests/Core/AWSSDKUtilsTests.cs
@@ -0,0 +1,40 @@
using Amazon.Runtime;
using Amazon.Util;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;

namespace UnitTests.NetStandard.Core
{
[Trait("Category", "Core")]
public class AWSSDKUtilsTests
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the #else block in the ToHex method is really just for .NET Framework can you copy the tests to the .NET Framework unit tests in the sdk\test\UnitTests\Custom folder. Hopefully as part of V4 we can do some test restructure cleanup so we don't have to copy the test between the .NET Framework and .NET Standard+.

{
[Fact]
public void BytesToHexString()
{
var bytes = Encoding.UTF8.GetBytes("Hello World");
var hexString = AWSSDKUtils.BytesToHexString(bytes);

Assert.Equal("48656C6C6F20576F726C64", hexString);
}

[Fact]
public void ToHexUppercase()
{
var bytes = Encoding.UTF8.GetBytes("Hello World");
var hexString = AWSSDKUtils.ToHex(bytes, false);

Assert.Equal("48656C6C6F20576F726C64", hexString);
}

[Fact]
public void ToHexLowercase()
{
var bytes = Encoding.UTF8.GetBytes("Hello World");
var hexString = AWSSDKUtils.ToHex(bytes, true);

Assert.Equal("48656c6c6f20576f726c64", hexString);
}
}
}