Fix evil allocations, marshaling overhead

StrToPtr() had at least 4 extra allocations of byte[] and char[] arrays that will make Unity's GC and frametime stability sad, taking into account you can updated 5 times per 20 seconds, which is few frames apart.
Also, there was 0 reason to have that marshaling invoke overhead where it zeroes byte by byte in a loop. There is no point, we already overwrite whole memory via .Copy() and we only allocate as much as needed, no extra. No security concerns here.
This commit is contained in:
Kein 2021-04-13 03:31:55 +03:00 committed by GitHub
parent 963aa9f3e5
commit f62dfa8f73
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -132,6 +132,8 @@ public class DiscordRpc
{
private RichPresenceStruct _presence;
private readonly List<IntPtr> _buffers = new List<IntPtr>(10);
private char[] _chrBuffer = new char[128];
private byte[] _byteBuffer = new byte[385]; // utf8 char max 4 bytes in worst case
public string state; /* max 128 bytes */
public string details; /* max 128 bytes */
@ -189,14 +191,12 @@ public class DiscordRpc
private IntPtr StrToPtr(string input)
{
if (string.IsNullOrEmpty(input)) return IntPtr.Zero;
var convbytecnt = Encoding.UTF8.GetByteCount(input);
var buffer = Marshal.AllocHGlobal(convbytecnt + 1);
for (int i = 0; i < convbytecnt + 1; i++)
{
Marshal.WriteByte(buffer, i, 0);
}
var len = input.Length > 128 ? 128 : input.Length;
input.CopyTo(0, _chrBuffer, 0, len);
var convbytecnt = Encoding.UTF8.GetBytes(_chrBuffer, 0, len, _byteBuffer, 0);
IntPtr buffer = Marshal.AllocHGlobal(convbytecnt + 1);
_buffers.Add(buffer);
Marshal.Copy(Encoding.UTF8.GetBytes(input), 0, buffer, convbytecnt);
Marshal.Copy(_byteBuffer, 0, buffer, convbytecnt);
return buffer;
}
@ -228,4 +228,4 @@ public class DiscordRpc
}
}
}
}
}