Skip to content

Commit 989ee9b

Browse files
committed
[GEOT-3394] ContentFeatureCollection.isEmpty(): improved performance using a query that returns at most 1 result instead of checking if size() == 0
1 parent 71d20b9 commit 989ee9b

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed

modules/library/data/src/main/java/org/geotools/data/store/ContentFeatureCollection.java

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -359,12 +359,8 @@ public int size() {
359359
} else {
360360
// we have to iterate, probably best if we do a minimal query that
361361
// only loads a short attribute
362-
AttributeDescriptor chosen = null;
363-
for (AttributeDescriptor ad : getSchema().getAttributeDescriptors()) {
364-
if(chosen == null || size(ad) < size(chosen)) {
365-
chosen = ad;
366-
}
367-
}
362+
AttributeDescriptor chosen = getSmallAttributeInSchema();
363+
368364
// build the minimal query
369365
Query q = new Query(query);
370366
if(chosen != null) {
@@ -392,6 +388,16 @@ public int size() {
392388
}
393389
}
394390

391+
private AttributeDescriptor getSmallAttributeInSchema() {
392+
AttributeDescriptor chosen = null;
393+
for (AttributeDescriptor ad : getSchema().getAttributeDescriptors()) {
394+
if (chosen == null || size(ad) < size(chosen)) {
395+
chosen = ad;
396+
}
397+
}
398+
return chosen;
399+
}
400+
395401
/**
396402
* Quick heuristic used to find a small attribute to use when
397403
* scanning over the entire collection just to get the size of the
@@ -422,7 +428,25 @@ int size(AttributeDescriptor ad) {
422428
}
423429

424430
public boolean isEmpty() {
425-
return size() == 0;
431+
// build a minimal query
432+
Query notEmptyQuery = new Query(query);
433+
notEmptyQuery.setMaxFeatures(1);
434+
435+
AttributeDescriptor smallAttribute = getSmallAttributeInSchema();
436+
if (smallAttribute != null) {
437+
notEmptyQuery.setPropertyNames(Collections.singletonList(smallAttribute.getLocalName()));
438+
}
439+
440+
try {
441+
FeatureReader fr = featureSource.getReader(notEmptyQuery);
442+
try {
443+
return !fr.hasNext();
444+
} finally {
445+
fr.close();
446+
}
447+
} catch (IOException e) {
448+
throw new RuntimeException(e);
449+
}
426450
}
427451

428452
public boolean add(SimpleFeature o) {

0 commit comments

Comments
 (0)