From 227b03e6b8d46f61d4a0d8df9a0526b5d6c99ee1 Mon Sep 17 00:00:00 2001
From: Sergey Prigogin <eclipse.sprigogin@gmail.com>
Date: Tue, 17 Dec 2013 20:18:42 -0800
Subject: [PATCH] An attempt at performance optimization.

Change-Id: Ia4b6839626381935af859ae468de418fa004c867
Reviewed-on: https://git.eclipse.org/r/19934
Reviewed-by: Nathan Ridge <zeratul976@hotmail.com>
Reviewed-by: Sergey Prigogin <eclipse.sprigogin@gmail.com>
IP-Clean: Sergey Prigogin <eclipse.sprigogin@gmail.com>
Tested-by: Sergey Prigogin <eclipse.sprigogin@gmail.com>
---
 .../cdt/core/parser/util/CollectionUtils.java | 27 ++++++++++++++-----
 1 file changed, 20 insertions(+), 7 deletions(-)

diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/parser/util/CollectionUtils.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/parser/util/CollectionUtils.java
index d93a69016ca..691d6adf199 100644
--- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/parser/util/CollectionUtils.java
+++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/parser/util/CollectionUtils.java
@@ -154,17 +154,30 @@ public final class CollectionUtils {
 	}
 	
     /**
-     * Filter the elements of a collection down to just the ones
-     * that match the given predicate.
+     * Filter the elements of a collection down to just the ones that match the given predicate.
 	 * @since 5.6
 	 */
 	public static <T> Collection<T> filter(Collection<T> collection, IUnaryPredicate<T> predicate) {
 		if (collection.isEmpty())
 			return collection;
-		Collection<T> result = new ArrayList<T>();
-		for (T t : collection)
-			if (predicate.apply(t))
-				result.add(t);
-		return result;
+		Collection<T> result = null;
+		int n = 0;
+		for (T t : collection) {
+			if (predicate.apply(t)) {
+				if (result != null) {
+					result.add(t);
+				} else {
+					++n;
+				}
+			} else if (result == null) {
+				result = new ArrayList<T>(collection.size() - 1);
+				for (T u : collection) {
+					if (--n < 0)
+						break;
+					result.add(u);
+				}
+			}
+		}
+		return result == null ? collection : result;
     }
 }