Skip to content

Commit 310005e

Browse files
Small ConvertPolyfill performance-improvements (#326)
1 parent 0739be5 commit 310005e

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

src/Polyfill/ConvertPolyfill.cs

+16-14
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public static string ToHexString(byte[] inArray, int offset, int length)
3535
if (offset > (inArray.Length - length))
3636
throw new ArgumentOutOfRangeException(nameof(offset));
3737

38-
var builder = new StringBuilder();
38+
var builder = new StringBuilder(length * 2);
3939

4040
var end = length + offset;
4141
for (int i = offset; i < end; i++)
@@ -65,7 +65,7 @@ public static string ToHexStringLower(byte[] inArray, int offset, int length)
6565
if (offset > (inArray.Length - length))
6666
throw new ArgumentOutOfRangeException(nameof(offset));
6767

68-
var builder = new StringBuilder();
68+
var builder = new StringBuilder(length * 2);
6969

7070
var end = length + offset;
7171
for (int i = offset; i < end; i++)
@@ -132,15 +132,16 @@ public static bool TryToHexString(ReadOnlySpan<byte> source, Span<char> destinat
132132
=> Convert.TryToHexString(source, destination, out charsWritten);
133133
#else
134134
{
135-
var hexString = ConvertPolyfill.ToHexString(source);
136-
if (hexString.TryCopyTo(destination))
135+
if (source.Length > destination.Length / 2)
137136
{
138-
charsWritten = hexString.Length;
139-
return true;
137+
charsWritten = 0;
138+
return false;
140139
}
141140

142-
charsWritten = 0;
143-
return false;
141+
var hexString = ConvertPolyfill.ToHexString(source);
142+
hexString.CopyTo(destination);
143+
charsWritten = hexString.Length;
144+
return true;
144145
}
145146
#endif
146147

@@ -153,15 +154,16 @@ public static bool TryToHexStringLower(ReadOnlySpan<byte> source, Span<char> des
153154
=> Convert.TryToHexStringLower(source, destination, out charsWritten);
154155
#else
155156
{
156-
var hexString = ConvertPolyfill.ToHexStringLower(source);
157-
if (hexString.TryCopyTo(destination))
157+
if (source.Length > destination.Length / 2)
158158
{
159-
charsWritten = hexString.Length;
160-
return true;
159+
charsWritten = 0;
160+
return false;
161161
}
162162

163-
charsWritten = 0;
164-
return false;
163+
var hexString = ConvertPolyfill.ToHexStringLower(source);
164+
hexString.CopyTo(destination);
165+
charsWritten = hexString.Length;
166+
return true;
165167
}
166168
#endif
167169

0 commit comments

Comments
 (0)