muppet9010 / Factorio-Splatter-Guard

Stops you being splattered by trains
https://mods.factorio.com/mod/splatter_guard
Other
1 stars 0 forks source link

performance inprovement ideas #10

Open muppet9010 opened 5 years ago

muppet9010 commented 5 years ago

from Aidiakapi in Discord:

Well, if you wanted to optimize it, there are many things you could do, like:

  • Do not create a manger per-player (array of structs), but turn it around, and combine processing on players (struct of arrays).
  • Separate the players into different buckets based on proximity to any track.
  • Create a sparse array, mapping chunk_id ((chunk_x << 16) | chunk_y) to the amount of track in that chunk. That way, you can query if the player is even near a chunk that has a track, all without touching the API. You only have to do some minor cheap updating when entities are created/removed, which happens relatively infrequently.
  • Update the player buckets with more distance way less frequently. Only update the bucket of players that's near a track often.
  • For the players that are in proximity of track, combine the surface queries (so you're not checking the same area multiple times for multiple players).
  • Even if players are in proximity, unless they're using heavily modded speeds (either player or train), there's no way that within 1 tick it can go from "being more than 32 tiles away", to "collision". This is another level at which you can separate the players out, where the "rough proximity" should be checked let's say every 10 frames, but the "shit there's a train really close" players can be checked every frame.

Would be a big undertaking though. Considering your performance is currently linear with the amount of players, it's likely not that big of an issue in single player. Regardless, it might be faster to run count_entities_filtered in methods likeTrain.GetTrainEntitiesNearPositionAsArray.

Also, in-general for Lua, if you really want to go fast, you use locals as much as possible. And like in most dynamic languages, allocations and function calls are relatively expensive. And in Lua, because of string interning, comparisons are really fast, but modifying strings is fairly slow.

muppet9010 commented 4 years ago

remove the on_entity_damaged event usage as this really doesn't scale well