Most efficient way to get nearby entities

Discussion in 'Plugin Development' started by mine2012craft, May 31, 2018.

Thread Status:
Not open for further replies.
  1. Offline

    mine2012craft

    Hello,

    So I'm looking for the fastest and best way to get nearby entities. So far I have three options:

    Option 1:

    Code:
    for (Entity e : loc.getWorld().getEntities()){
                                if (e.getLocation().distance(loc) < 1.5){
    Option 2:

    Code:
    for (Entity e : loc.getWorld().getNearbyEntities(loc, 1, 1, 1)) {
    
    //OR (for non-location stuff)
    
    List <Entity> entities = player.getNearbyEntities(2D,3D,2D);
    Option 3:

    Code:
    //Works for both, filters all unnecessary entities (ArmorStands only right now)
    
    for (Entity e : MiniUtils.filterEntities(loc.getWorld().getNearbyEntities(loc, 7.5, 3, 7.5))) {
    
    //filterEntities
    public static Collection<Entity> filterEntities(Collection<Entity> entities) {
            List<Entity> toRemove = new ArrayList<Entity>();
            for (Entity e : entities) {
                if (e instanceof ArmorStand)
                    toRemove.add(e);
            }
            entities.removeAll(toRemove);
         
            return entities;
        }
    What I'm doing with these by the way is damaging, and also using these in BukkitRunnables ranging from a tick rate of 1-10, while also dealing with decently large packs of monsters that utilize armor stand names and HP Bars (Ya, not the best way, I understand)
    I'm not so sure which is the best way and the less lag-intensive. Is there anyone who could give me pointers onto which one is best?

    Thank you!
     
  2. Offline

    Zombie_Striker

    @mine2012craft
    #1 loops through all the entities in the world, even if they are no where near the player.

    #2, if I'm correctly, only checks for the entities in or around the player's chunk, which is the best option if you are only going to do this once.

    #3 is the same as #2, but does the filtering outside of the for loop. This is useful if you need to check the entities in multiple places.
     
Thread Status:
Not open for further replies.

Share This Page