We are running a public server with this mod, and in the last few days we've created 30 subsurfaces, and it's been observed that the game stutters. When I walk around, about every second, the game freeze for like 0.1 seconds. The debug options show Subsurface script update time jumping between 1ms to 2ms so it was suspected it was this mod, but we didn't know exactly which lines / functionality caused it.
In the last couple of days I wrote a flame graph profiler to know exactly what's causing it. This is the report of 1000 samples: https://gist.github.com/zhuyifei1999/b4e841c25f1385d7b3f5c997fd9878e2 (The test is running on 1.1.17 of this mod because the server hasn't updated)
The reports shows 7.6% of samples in __Subsurface__/control.lua:401 and 4.2% of samples in __Subsurface__/control.lua:402. (The profiler I wrote has a lot of overhead as it's currently written, but the overall proportion should not change.) In other words, 11.8% of the time, Factorio is running these two lines:
for _, e in ipairs(subsurface.find_entities_filtered{type = attrition_types}) do
if subsurface.get_pollution(e.position) > attrition_threshold and math.random(5) == 1 then e.damage(e.max_health * 0.01, game.forces.neutral, "physical") end
These two lines are concentrated on one tick out of every 64 ticks, so the effects are extremely noticeable.
Looking at the code, I think the common case should be that there is no pollution damage, so instead of iterating all valid entities on the surface, can I suggest iterating pollution chunks first, then search for entities on those chunks and damage them?