Targeting()
var/list/l=orange(8,src)
src.target=null
for(var/atom/movable/A in l)
if(src.TargetECheck(A))
src.target=A
break
Problem description:
Basically AI code is causing lots of cpu, I'm pretty sure its cuz of the looking thru the view/range. The reason I have it looking for a movable atom is cause they are able to target/attack objs aswell. When it comes to this type of code do you know bypasses or alternatives.
Also I would like to note I originally had it loop thru view() which was much worse, and I remember a recent post where kaiochao was mentioning view has to look for visibility etc, so I was like maybe range is more efficient. I just thought this was very counterintuitive since one would expect range to pick up more objects which in return will create a longer list to loop. Please share any ideas.
How often are you calling this code?
How much is "lots of CPU?"
How many mobs are using this function at once?
Just because it's an intense function doesn't mean the optimization needs to happen that function itself. Sometimes, it's better to leave the function well enough alone and find other methods of optimizing simply by calling the function less often, or maintaining data that eliminates the need for calling the function all the time.
One initial pointer for optimization though, is this:
Not every movable atom needs to be targetable. Simply defining a variable to prevent TargetECheck() will prevent a lot of proc call overhead before finding a worthy target. That's a very simple optimization.
Another, higher effort optimization is investigating a quadtree rather than looping through view. Track the movements of all targetable atoms and maintain their position in a quadtree. Find the smallest tree node that the AI's range covers and then loop through all targetable atoms in that quadtree's tracked objects list and check targetability manually. This will reduce quite a lot of list generation and manipulation, which is the source of the slowness.
I have no good advice as far as building quadtrees in DM. I've done it a few times, but you will really want to understand the theory yourself before you tackle such a project. Read up on quadtrees and Binary Space Partitioning.