From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Andrew Steinborn <git@steinborn.me>
Date: Mon, 9 Aug 2021 00:38:37 -0400
Subject: [PATCH] Optimize indirect passenger iteration


diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index aac47d2de2825b46e54ad936a48c96ef7f6703e1..66ddae628d8ccce62aa6937166d719911aef44a2 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -3870,20 +3870,34 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess
     }
 
     private Stream<Entity> getIndirectPassengersStream() {
+        if (this.passengers.isEmpty()) { return Stream.of(); } // Paper - Optimize indirect passenger iteration
         return this.passengers.stream().flatMap(Entity::getSelfAndPassengers);
     }
 
     @Override
     public Stream<Entity> getSelfAndPassengers() {
+        if (this.passengers.isEmpty()) { return Stream.of(this); } // Paper - Optimize indirect passenger iteration
         return Stream.concat(Stream.of(this), this.getIndirectPassengersStream());
     }
 
     @Override
     public Stream<Entity> getPassengersAndSelf() {
+        if (this.passengers.isEmpty()) { return Stream.of(this); } // Paper - Optimize indirect passenger iteration
         return Stream.concat(this.passengers.stream().flatMap(Entity::getPassengersAndSelf), Stream.of(this));
     }
 
     public Iterable<Entity> getIndirectPassengers() {
+        // Paper start - Optimize indirect passenger iteration
+        if (this.passengers.isEmpty()) { return ImmutableList.of(); }
+        ImmutableList.Builder<Entity> indirectPassengers = ImmutableList.builder();
+        for (Entity passenger : this.passengers) {
+            indirectPassengers.add(passenger);
+            indirectPassengers.addAll(passenger.getIndirectPassengers());
+        }
+        return indirectPassengers.build();
+    }
+    private Iterable<Entity> getIndirectPassengers_old() {
+        // Paper end - Optimize indirect passenger iteration
         return () -> {
             return this.getIndirectPassengersStream().iterator();
         };
@@ -3896,6 +3910,7 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess
     }
 
     public boolean hasExactlyOnePlayerPassenger() {
+        if (this.passengers.isEmpty()) { return false; } // Paper - Optimize indirect passenger iteration
         return this.countPlayerPassengers() == 1;
     }
 
