ID:2225368
 
(See the best response by Kaiochao.)
for(var/mob/m in world) <- this executes very fast
for(var/mob/m in range(mob,10)) <- while this executes too slow

shouldn't the situation be reversed??
Also certain objects take much longer to search even though there are fewer in the map.

for(var/mob/Unit/u in world){} <- 0ms lag
for(var/obj/Town/t in world){} <- 4ms lag

Why does this happens, I have only 7 towns and around 20 Units. Maybe when searching for towns it searches all obj types??


(using 32 world size)
Best response
When searching for any type of a base atom type, it only needs to search through a list for that particular base atom type. I'm 90% sure about this. It probably isn't documented anywhere, but I recall there being several posts on the subject... so I'm rolling with it.

For instance, searching for all /obj/Town searches through all /obj, and only applies the body of the loop if istype(t, /obj/Town). It doesn't search through mobs or any other type. So, if you have a lot more objs of any type in the world than mobs of any type, it makes sense that the search for objs would take longer.

In general, avoid searching the entire world for something, because you never know how big the world will get. If you keep a list of the things you need, then it doesn't matter how large the world will get, because you never have to filter through any of it.

Example:
// global list of towns
var list/towns = new

obj/Town

// on creation, add the town to the global list of towns
New()
towns += src
// ...

// on destruction, remove the town from the global list of towns
// (otherwise the reference in towns becomes a null instead)
Del()
towns -= src
..()


As for why range() is slower, it's probably because range() has to build a list of all atoms in range before you even start to iterate through it. For a range of 10, this list would contain at least 441 turfs, an area, and some number of objs and mobs. Compared to looping over a list of mobs that (presumably) already exists internally, this is much more expensive.
Thanks for the explanation I've already started creating lists I just wanted to make sure that this was not a bug of any kind yeah I have totally far more obj than mob, so that makes sense.