Skip to content

Commit

Permalink
Optimise Database.FormatHash
Browse files Browse the repository at this point in the history
runtime (as reported by `Database`) reduced by -14%, allocations reduced
by -5%, and number of calls reduced by -32%
this is all under Mono so YMMV
  • Loading branch information
YoshiRulz committed Dec 15, 2024
1 parent be0736b commit 8645ed3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
21 changes: 21 additions & 0 deletions src/BizHawk.Common/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,27 @@ public static byte[] ToCharCodepointArray(this string str)
return a;
}

/// <summary>as <see cref="string.ToUpperInvariant"/>, but assumes <paramref name="str"/> is 7-bit ASCII to allow for an optimisation</summary>
/// <remarks>allocates a new char array only when necessary</remarks>
public static string ToUpperASCIIFast(this string str)
{
const ushort ASCII_UPCASE_MASK = 0b101111;
for (var i = 0; i < str.Length; i++)
{
if (str[i] is < 'a' or > 'z') continue;
var a = new char[str.Length];
str.AsSpan(start: 0, length: i).CopyTo(a);
a[i] = unchecked((char) (str[i] & ASCII_UPCASE_MASK));
while (++i < str.Length)
{
var c = str[i];
a[i] = c is >= 'a' and <= 'z' ? unchecked((char) (c & ASCII_UPCASE_MASK)) : c;
}
return new(a);
}
return str;
}

/// <summary>
/// splits a given <paramref name="str"/> by <paramref name="delimiter"/>,
/// applies <paramref name="transform"/> to each part, then rejoins them
Expand Down
5 changes: 4 additions & 1 deletion src/BizHawk.Emulation.Common/Database/Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ public static class Database
/// <param name="hash">The hash to format, this is typically prefixed with a type (e.g. sha1:)</param>
/// <returns>formatted hash</returns>
private static string FormatHash(string hash)
=> hash.Substring(hash.IndexOf(':') + 1).ToUpperInvariant();
{
var i = hash.IndexOf(':');
return (i < 0 ? hash.Substring(startIndex: i + 1) : hash).ToUpperASCIIFast();
}

private static void LoadDatabase_Escape(string line, bool inUser, bool silent)
{
Expand Down

0 comments on commit 8645ed3

Please sign in to comment.