Extensive garbage collection when using an event
with a connection from script
#568
-
Hi, We have a game server instance running in JS which is managed from C# code. Knowing how expensive interop between C# and JS is, I have reduced the interaction scope to a minimum, however I can't figure out if it's possible to reduce the GC pressure and amount of allocations produced by C# code when invoking an event handler. Specifically, the code looks something like this: public delegate void OnGameTick(double time);
public event OnGameTick? Tick;
public void Start() {
gameScript.Start();
var remainingTimeLimitMs = 0L;
var time = Stopwatch.StartNew();
while (true) {
var tickTimeMs = 33L;
while (remainingTimeLimitMs >= tickTimeMs) {
Tick?.Invoke(gameTime);
gameTime += (tickTimeMs / 1000d);
remainingTimeLimitMs -= tickTimeMs;
}
Thread.Sleep((int) tickTimeMs);
remainingTimeLimitMs += time.ElapsedMilliseconds;
time.Restart();
}
} And the script trivially connects to the GameScript.Tick.connect(time => {
GameRules.SetGameTime(time);
update();
}); Now, the call to |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 10 replies
-
Hi @DoctorGester,
Hmm, can you tell what all those objects are? Also, do you know approximately how many events your application fires per minute? Thanks! |
Beta Was this translation helpful? Give feedback.
Hi @DoctorGester,
We've looked at this and found that the even the best OS sleep primitives are a bit unpredictable, at least on Windows, so the function we're adding looks like this:
If
precise
isfalse
or unspecified,sleep
uses an OS sleep primitive. Ifprecise
istrue
, it performs a "cooperative spin wait", which provides excellent precision at the cost of mild CPU load (≤3% in our tests).Additionally, we're adding a way to increase native timer resolution, enhancing the precision of the OS sleep primitive. It's only effective on Windows, but Linux and macOS don't seem to need it anyway.