浏览代码

Improve Iterators.single (#122875)

Using an anonymous class here doesn't compile as expected.
The resulting class comes out as:

```
class Iterators$1 implements java.util.Iterator<T> {
  private T value;

  final java.lang.Object val$element;

  Iterators$1(java.lang.Object);
```

which seemingly also does not get fixed by the JIT compiler, judging by
heap dumps. Lets just use a named class to clean this up and make things
a bit more compact and save some heap as well here and there potentially.
Armin Braun 7 月之前
父节点
当前提交
b4f84f6f04
共有 1 个文件被更改,包括 18 次插入14 次删除
  1. 18 14
      server/src/main/java/org/elasticsearch/common/collect/Iterators.java

+ 18 - 14
server/src/main/java/org/elasticsearch/common/collect/Iterators.java

@@ -34,22 +34,27 @@ public class Iterators {
      * Returns a single element iterator over the supplied value.
      * Returns a single element iterator over the supplied value.
      */
      */
     public static <T> Iterator<T> single(T element) {
     public static <T> Iterator<T> single(T element) {
-        return new Iterator<>() {
+        return new SingleIterator<>(element);
+    }
 
 
-            private T value = Objects.requireNonNull(element);
+    private static final class SingleIterator<T> implements Iterator<T> {
+        private T value;
 
 
-            @Override
-            public boolean hasNext() {
-                return value != null;
-            }
+        SingleIterator(T element) {
+            value = Objects.requireNonNull(element);
+        }
 
 
-            @Override
-            public T next() {
-                final T res = value;
-                value = null;
-                return res;
-            }
-        };
+        @Override
+        public boolean hasNext() {
+            return value != null;
+        }
+
+        @Override
+        public T next() {
+            final T res = value;
+            value = null;
+            return res;
+        }
     }
     }
 
 
     @SafeVarargs
     @SafeVarargs
@@ -496,5 +501,4 @@ public class Iterators {
         }
         }
         return result;
         return result;
     }
     }
-
 }
 }