Best way to find ents within a certain distance

What is the best (most efficient) way to find entities within a certain position? Is it better to find all the entities of that specific class and then filter out the ones beyond the distance, or is it better to do a FindInSphere? The number of ents I’d be looking for of that class ranges from about 50 to 400 and I’d say at most they could be about 5000 units away while the distance I’d be constrained to looking for is 200units.
The reason I’m asking is because I do a check every second of these ents to see if I should give the player money if they are within a certain distance of the ents. So although it isn’t running every tick it still seems like a lot of work to do every second.

I was also wondering if someone knows a good place that talks about lua optimization and what gmod function are good and bad for efficiency. Right now I’m just having issues when there are over 26 people on the server and there are a lot of entities(props) on the map

I’d use FindInSphere.

FindInSphere isn’t THAT much of a stress on the CPU. I’m pretty sure calling that function every second is completely safe, even if you have quite a bit of entities.

Entity.SetNetworkedVariable is of the devil. Try to use it only when absolutely needed.

I use it for player stats and a few other very small things. What would be a better alternative?

It’s not so much that, but more that you need to understand how NW vars work.

Whenever you set a NW var, you usermessage it to all currently connected players, and then its stored, so when new players connect, they get usermessage’d that NW var.

So, whenever you set a NW var, you’re effectively just usermessage’ing all connected players. The only time a NW var is effective is when all players need to have that var networked. Elsewise, use usermessages to send it to the clients that need it.

Wow never knew that. Thank you! I do use it for a couple of my SWEPs which then isn’t needed since it is for that person only. The stats still need it since that is displayed to everyone.

Hint: Don’t use NWVars. Use umsgs instead.

[editline]14th February 2012[/editline]

Unless garry updated how they work?