]> source.dussan.org Git - vaadin-framework.git/commitdiff
Improve performance of Util.collectionEquals (#16968).
authorFabian Lange <lange.fabian@gmail.com>
Mon, 2 Mar 2015 11:16:19 +0000 (12:16 +0100)
committerVaadin Code Review <review@vaadin.com>
Mon, 2 Mar 2015 13:44:28 +0000 (13:44 +0000)
This change checks the length of both collections first before iterating
them. This massively speeds up the comparison in case the collections do
not have the same length.

Also in the case where the lengths are equal, this saves the
collection2.hasNext() checks.

Change-Id: If1325f3581d12bf742d77fbf8b0f89511fa11252

client/src/com/vaadin/client/Util.java

index 778f7c38611882f0c3efecd6b4331d7333a07b2a..99e6507d813bb4833cd55219403ca8716e55b88e 100644 (file)
@@ -825,30 +825,29 @@ public class Util {
      * @return true if the collections contain the same elements in the same
      *         order, false otherwise
      */
-    public static boolean collectionsEquals(Collection collection1,
-            Collection collection2) {
+    public static boolean collectionsEquals(Collection<?> collection1,
+            Collection<?> collection2) {
         if (collection1 == null) {
             return collection2 == null;
         }
         if (collection2 == null) {
             return false;
         }
-        Iterator<Object> collection1Iterator = collection1.iterator();
-        Iterator<Object> collection2Iterator = collection2.iterator();
+
+        if (collection1.size() != collection2.size()) {
+            return false;
+        }
+
+        Iterator<?> collection1Iterator = collection1.iterator();
+        Iterator<?> collection2Iterator = collection2.iterator();
 
         while (collection1Iterator.hasNext()) {
-            if (!collection2Iterator.hasNext()) {
-                return false;
-            }
             Object collection1Object = collection1Iterator.next();
             Object collection2Object = collection2Iterator.next();
             if (collection1Object != collection2Object) {
                 return false;
             }
         }
-        if (collection2Iterator.hasNext()) {
-            return false;
-        }
 
         return true;
     }