These two examples in particular seem to search for entities in a given area. Queries like that can often be sped up considerably by storing entities (or at least references to them) in a data-structure optimized for spacial queries.
Two common options are various variants of spacial trees or spatial hashing.
OptionsExample of options for spacial trees are quadtrees or k-d trees. What most trees have in common is that it is pretty quick to get all entities within an given rectangular area, but it's usually a rather expensive operation to move entities, because doing so can require to recalculate large sections of the tree. That makes them most useful for immobile entities.
Spatial hashing means that you divide your game world into a grid of rectangular sections and then have a list for every section with the entities which are currently in that section. You store those sections in a 2-dimensional array, so acquiring a section by coordinates is a very fast operation. When you want to check against all entities around the player, you only need to iterate the lists of the section the player is in and adjacent sections.