Skip to content

Commit a120b38

Browse files
committed
Reduce allocations in converting to message
1 parent 3388f68 commit a120b38

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

tracer/src/Datadog.Trace/LibDatadog/Error.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
#nullable enable
77

8+
using System;
89
using System.Runtime.InteropServices;
910
using System.Text;
1011
using Datadog.Trace.Logging;
@@ -25,8 +26,6 @@ internal readonly struct Error
2526

2627
public LibDatadogException ToException()
2728
{
28-
var messageBytes = Message.ToByteArray();
29-
var message = Encoding.UTF8.GetString(messageBytes);
30-
return new LibDatadogException(message);
29+
return new LibDatadogException(Message.ToUtf8String());
3130
}
3231
}

tracer/src/Datadog.Trace/LibDatadog/FFIVec.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
using System;
99
using System.Runtime.InteropServices;
10+
using System.Text;
1011

1112
namespace Datadog.Trace.LibDatadog;
1213

@@ -17,10 +18,16 @@ internal readonly struct FFIVec
1718
internal readonly nuint Length;
1819
internal readonly nuint Capacity;
1920

20-
public byte[] ToByteArray()
21+
public string ToUtf8String()
2122
{
22-
var bytes = new byte[Length];
23-
Marshal.Copy(Data, bytes, 0, (int)Length);
24-
return bytes;
23+
unsafe
24+
{
25+
#if NETCOREAPP
26+
var messageBytes = new ReadOnlySpan<byte>(Data.ToPointer(), (int)Length);
27+
return Encoding.UTF8.GetString(messageBytes);
28+
#else
29+
return Encoding.UTF8.GetString((byte*)Data.ToPointer(), (int)Length);
30+
#endif
31+
}
2532
}
2633
}

0 commit comments

Comments
 (0)