Task.Run() garbage frame time spikes

I’m running an async method and it apparantly allocates a lot of garbage and creates massive frame time spikes. The spikes show up as Other and EditorLoop and not as GC but still I assume that’s GC.

protected override JobHandle OnUpdate(JobHandle handle)
    {
        Entities.ForEach((MapMagicReference mmr) => { _mm = mmr.Value; }).WithoutBurst().Run();

        if (!_generating)
        {
            GenerateMap(_mm);
        }
        return handle;
    }

    async private Task GenerateMap(MapMagic.MapMagic mm)
    {
        await Task.Run(() =>
        {
            _generating = true;
            var coordRect = new CoordRect(new Coord(0, 0), new Coord(128, 128));
            var results = new Chunk.Results();
            var borderSize = 16;
            var generateSize = 64;
            var size = new Chunk.Size(generateSize, generateSize, generateSize);
            var seed = 0;
            mm.gens.Calculate(coordRect, results, size, seed);
            _generating = false;
        });
    }

What can I do to avoid the garbage but still run my method Async().

This might have nothing to do with that async task lamda. This might just be the method call inside it that generates the garbage. I’m investigating.

I know those spikes :wink: that’s the Profiler Window repainting, which isn’t happening every frame but only every couple of frames to reduce the general EditorLoop overhead when profiling the Editor or Playmode. BTW, if you ever want to see what is happening inside of the EditorLoop, switch the target from Playmode to Editor. To see you games performance without this overhead, make a development build and profile that.

That said, it does seem to coincide with GC collection. Maybe repainting the Profiler puts the Memory pressure on to cause a GC within the Editor code, which is why you might not see it when targeting Playmode. So yes, try profiling the Editor while playing in Playmode. You might want to turn on call stacks collection and let the Profiler window show the memory usage details instead of the CPU usage views while profiling.

Have you resolved this?

So that was the editor? Profiler repaint. That makes sense. Thanks, @MartinTilo

Close (or stop) the profiler and it shouldn’t be a problem? But really, as @MartinTilo said, profile the editor to see if that’s the editor.

1 Like