Skip to content

Commit bb052f0

Browse files
committed
Optimzed quad tree and cluster algorithm with HashSet instead of ArrayList
ArrayList.remove() is a much more expensive operation than HashSet.remove(). Neither of these collections need to be an array, as neither order nor duplicate entries are required. A set collection is much more optimal with very noticeable speed improvements with large sets of cluster items.
1 parent f7320a8 commit bb052f0

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

library/src/com/google/maps/android/clustering/algo/NonHierarchicalDistanceBasedAlgorithm.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public class NonHierarchicalDistanceBasedAlgorithm<T extends ClusterItem> implem
5252
/**
5353
* Any modifications should be synchronized on mQuadTree.
5454
*/
55-
private final Collection<QuadItem<T>> mItems = new ArrayList<QuadItem<T>>();
55+
private final Collection<QuadItem<T>> mItems = new HashSet<>();
5656

5757
/**
5858
* Any modifications should be synchronized on mQuadTree.

library/src/com/google/maps/android/quadtree/PointQuadTree.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121

2222
import java.util.ArrayList;
2323
import java.util.Collection;
24+
import java.util.HashSet;
2425
import java.util.List;
26+
import java.util.Set;
2527

2628
/**
2729
* A quad tree which tracks items with a Point geometry.
@@ -50,7 +52,7 @@ public interface Item {
5052
/**
5153
* The elements inside this quad, if any.
5254
*/
53-
private List<T> mItems;
55+
private Set<T> mItems;
5456

5557
/**
5658
* Maximum depth.
@@ -115,7 +117,7 @@ private void insert(double x, double y, T item) {
115117
return;
116118
}
117119
if (mItems == null) {
118-
mItems = new ArrayList<T>();
120+
mItems = new HashSet<>();
119121
}
120122
mItems.add(item);
121123
if (mItems.size() > MAX_ELEMENTS && mDepth < MAX_DEPTH) {
@@ -133,7 +135,7 @@ private void split() {
133135
mChildren.add(new PointQuadTree<T>(mBounds.minX, mBounds.midX, mBounds.midY, mBounds.maxY, mDepth + 1));
134136
mChildren.add(new PointQuadTree<T>(mBounds.midX, mBounds.maxX, mBounds.midY, mBounds.maxY, mDepth + 1));
135137

136-
List<T> items = mItems;
138+
Set<T> items = mItems;
137139
mItems = null;
138140

139141
for (T item : items) {
@@ -211,7 +213,7 @@ private void search(Bounds searchBounds, Collection<T> results) {
211213
}
212214
} else if (mItems != null) {
213215
if (searchBounds.contains(mBounds)) {
214-
results.addAll(mItems);
216+
results.addAll(mItems);
215217
} else {
216218
for (T item : mItems) {
217219
if (searchBounds.contains(item.getPoint())) {

0 commit comments

Comments
 (0)