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:
parent
963aa9f3e5
commit
f62dfa8f73
@ -132,6 +132,8 @@ public class DiscordRpc
|
|||||||
{
|
{
|
||||||
private RichPresenceStruct _presence;
|
private RichPresenceStruct _presence;
|
||||||
private readonly List<IntPtr> _buffers = new List<IntPtr>(10);
|
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 state; /* max 128 bytes */
|
||||||
public string details; /* max 128 bytes */
|
public string details; /* max 128 bytes */
|
||||||
@ -189,14 +191,12 @@ public class DiscordRpc
|
|||||||
private IntPtr StrToPtr(string input)
|
private IntPtr StrToPtr(string input)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(input)) return IntPtr.Zero;
|
if (string.IsNullOrEmpty(input)) return IntPtr.Zero;
|
||||||
var convbytecnt = Encoding.UTF8.GetByteCount(input);
|
var len = input.Length > 128 ? 128 : input.Length;
|
||||||
var buffer = Marshal.AllocHGlobal(convbytecnt + 1);
|
input.CopyTo(0, _chrBuffer, 0, len);
|
||||||
for (int i = 0; i < convbytecnt + 1; i++)
|
var convbytecnt = Encoding.UTF8.GetBytes(_chrBuffer, 0, len, _byteBuffer, 0);
|
||||||
{
|
IntPtr buffer = Marshal.AllocHGlobal(convbytecnt + 1);
|
||||||
Marshal.WriteByte(buffer, i, 0);
|
|
||||||
}
|
|
||||||
_buffers.Add(buffer);
|
_buffers.Add(buffer);
|
||||||
Marshal.Copy(Encoding.UTF8.GetBytes(input), 0, buffer, convbytecnt);
|
Marshal.Copy(_byteBuffer, 0, buffer, convbytecnt);
|
||||||
return buffer;
|
return buffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -228,4 +228,4 @@ public class DiscordRpc
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user