Skip to content

Initialize lists with size where possible. #3974

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.4.0-SNAPSHOT</version>
<version>3.4.0-GH-3941-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data MongoDB</name>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-benchmarks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.4.0-SNAPSHOT</version>
<version>3.4.0-GH-3941-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.4.0-SNAPSHOT</version>
<version>3.4.0-GH-3941-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.4.0-SNAPSHOT</version>
<version>3.4.0-GH-3941-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,16 +176,20 @@ private static Document createGeoWithin(String key, Document source, @Nullable O
Document $geoWithinMin = new Document("$geoWithin",
new Document(spheric ? "$centerSphere" : "$center", $centerMin));

List<Document> criteria = new ArrayList<>();
List<Document> criteria;

if ($and != null) {
if ($and instanceof Collection) {
criteria.addAll((Collection) $and);
Collection andElements = (Collection) $and;
criteria = new ArrayList<>(andElements.size() + 2);
criteria.addAll(andElements);
} else {
throw new IllegalArgumentException(
"Cannot rewrite query as it contains an '$and' element that is not a Collection!: Offending element: "
+ $and);
}
} else {
criteria = new ArrayList<>(2);
}

criteria.add(new Document("$nor", Collections.singletonList(new Document(key, $geoWithinMin))));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ public List<IndexInfo> doInCollection(MongoCollection<Document> collection)

private List<IndexInfo> getIndexData(MongoCursor<Document> cursor) {

List<IndexInfo> indexInfoList = new ArrayList<>();
int available = cursor.available();
List<IndexInfo> indexInfoList = available > 0 ? new ArrayList<>(available) : new ArrayList<>();

while (cursor.hasNext()) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -966,7 +966,7 @@ public <T> GeoResults<T> geoNear(NearQuery near, Class<?> domainType, String col
DocumentCallback<GeoResult<T>> callback = new GeoNearResultDocumentCallback<>(distanceField,
new ProjectingReadCallback<>(mongoConverter, projection, collection), near.getMetric());

List<GeoResult<T>> result = new ArrayList<>();
List<GeoResult<T>> result = new ArrayList<>(results.getMappedResults().size());

BigDecimal aggregate = BigDecimal.ZERO;
for (Document element : results) {
Expand Down Expand Up @@ -1327,7 +1327,7 @@ protected <T> Collection<T> doInsertBatch(String collectionName, Collection<? ex

Assert.notNull(writer, "MongoWriter must not be null!");

List<Document> documentList = new ArrayList<>();
List<Document> documentList = new ArrayList<>(batchToSave.size());
List<T> initializedBatchToSave = new ArrayList<>(batchToSave.size());
for (T uninitialized : batchToSave) {

Expand Down Expand Up @@ -2869,7 +2869,8 @@ private <T> List<T> executeFindMultiInternal(CollectionCallback<FindIterable<Doc
.initiateFind(getAndPrepareCollection(doGetDatabase(), collectionName), collectionCallback::doInCollection)
.iterator()) {

List<T> result = new ArrayList<>();
int available = cursor.available();
List<T> result = available > 0 ? new ArrayList<>(available) : new ArrayList<>();

while (cursor.hasNext()) {
Document object = cursor.next();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1586,7 +1586,7 @@ protected Flux<ObjectId> insertDocumentList(String collectionName, List<Document
LOGGER.debug(String.format("Inserting list of Documents containing %d items", dbDocList.size()));
}

List<Document> documents = new ArrayList<>();
List<Document> documents = new ArrayList<>(dbDocList.size());

return execute(collectionName, collection -> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -675,10 +675,7 @@ private Object resolveCriteria(AggregationOperationContext context, Object value
if (value instanceof CriteriaDefinition) {

Document mappedObject = context.getMappedObject(((CriteriaDefinition) value).getCriteriaObject());
List<Object> clauses = new ArrayList<Object>();

clauses.addAll(getClauses(context, mappedObject));

List<Object> clauses = getClauses(context, mappedObject);
return clauses.size() == 1 ? clauses.get(0) : clauses;
}

Expand All @@ -705,7 +702,9 @@ private List<Object> getClauses(AggregationOperationContext context, String key,

if (predicate instanceof List) {

List<Object> args = new ArrayList<Object>();
List<?> predicates = (List<?>) predicate;
List<Object> args = new ArrayList<Object>(predicates.size());

for (Object clause : (List<?>) predicate) {
if (clause instanceof Document) {
args.addAll(getClauses(context, (Document) clause));
Expand All @@ -723,14 +722,14 @@ private List<Object> getClauses(AggregationOperationContext context, String key,
continue;
}

List<Object> args = new ArrayList<Object>();
List<Object> args = new ArrayList<Object>(2);
args.add("$" + key);
args.add(nested.get(s));
clauses.add(new Document(s, args));
}
} else if (!isKeyword(key)) {

List<Object> args = new ArrayList<Object>();
List<Object> args = new ArrayList<Object>(2);
args.add("$" + key);
args.add(predicate);
clauses.add(new Document("$eq", args));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public static ExposedFields nonSynthetic(Fields fields) {
private static ExposedFields createFields(Fields fields, boolean synthetic) {

Assert.notNull(fields, "Fields must not be null!");
List<ExposedField> result = new ArrayList<ExposedField>();
List<ExposedField> result = new ArrayList<ExposedField>(fields.size());

for (Field field : fields) {
result.add(new ExposedField(field, synthetic));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ public Fields and(Fields fields) {
return result;
}

public int size() {
return fields.size();
}

@Nullable
public Field getField(String name) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public List<Document> toPipelineStages(AggregationOperationContext context) {
Document command = toDocument(context);
Number limit = (Number) command.get("$geoNear", Document.class).remove("num");

List<Document> stages = new ArrayList<>();
List<Document> stages = new ArrayList<>(3);
stages.add(command);

if (nearQuery.getSkip() != null && nearQuery.getSkip() > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public List<Document> bulkFetch(List<DBRef> refs) {

List<Document> result = mongoCollection //
.find(new Document(BasicMongoPersistentProperty.ID_FIELD_NAME, new Document("$in", ids))) //
.into(new ArrayList<>());
.into(new ArrayList<>(ids.size()));

return ids.stream() //
.flatMap(id -> documentWithId(id, result)) //
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ public Document convert(GeoCommand source) {
return null;
}

List argument = new ArrayList();
List argument = new ArrayList(2);

Shape shape = source.getShape();

Expand All @@ -489,7 +489,9 @@ public Document convert(GeoCommand source) {

} else if (shape instanceof Polygon) {

for (Point point : ((Polygon) shape).getPoints()) {
List<Point> points = ((Polygon) shape).getPoints();
argument = new ArrayList(points.size());
for (Point point : points) {
argument.add(toList(point));
}

Expand Down Expand Up @@ -824,7 +826,7 @@ static List<Double> toList(Point point) {
@SuppressWarnings("unchecked")
static List<Point> toListOfPoint(List listOfCoordinatePairs) {

List<Point> points = new ArrayList<>();
List<Point> points = new ArrayList<>(listOfCoordinatePairs.size());

for (Object point : listOfCoordinatePairs) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1052,14 +1052,14 @@ protected List<Object> createCollection(Collection<?> collection, MongoPersisten
}).collect(Collectors.toList());

return writeCollectionInternal(targetCollection, ClassTypeInformation.from(DocumentPointer.class),
new ArrayList<>());
new ArrayList<>(targetCollection.size()));
}

if (property.hasExplicitWriteTarget()) {
return writeCollectionInternal(collection, new FieldTypeInformation<>(property), new ArrayList<>());
return writeCollectionInternal(collection, new FieldTypeInformation<>(property), new ArrayList<>(collection.size()));
}

return writeCollectionInternal(collection, property.getTypeInformation(), new ArrayList<>());
return writeCollectionInternal(collection, property.getTypeInformation(), new ArrayList<>(collection.size()));
}

List<Object> dbList = new ArrayList<>(collection.size());
Expand Down Expand Up @@ -1144,7 +1144,9 @@ private List<Object> writeCollectionInternal(Collection<?> source, @Nullable Typ
collection.add(getPotentiallyConvertedSimpleWrite(element,
componentType != null ? componentType.getType() : Object.class));
} else if (element instanceof Collection || elementType.isArray()) {
collection.add(writeCollectionInternal(BsonUtils.asCollection(element), componentType, new ArrayList<>()));

Collection<?> objects = BsonUtils.asCollection(element);
collection.add(writeCollectionInternal(objects, componentType, new ArrayList<>(objects.size())));
} else {
Document document = new Document();
writeInternal(element, document, componentType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ protected Document getMappedKeyword(Keyword keyword, @Nullable MongoPersistentEn
if (keyword.isOrOrNor() || (keyword.hasIterableValue() && !keyword.isGeometry())) {

Iterable<?> conditions = keyword.getValue();
List<Object> newConditions = new ArrayList<>();
List<Object> newConditions = conditions instanceof Collection ? new ArrayList<>(((Collection<?>) conditions).size()) : new ArrayList<>();

for (Object condition : conditions) {
newConditions.add(isDocument(condition) ? getMappedObject((Document) condition, entity)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ public Criteria nin(Collection<?> values) {
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/mod/">MongoDB Query operator: $mod</a>
*/
public Criteria mod(Number value, Number remainder) {
List<Object> l = new ArrayList<Object>();
List<Object> l = new ArrayList<Object>(2);
l.add(value);
l.add(remainder);
criteria.put("$mod", l);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,10 @@ public Object nextConverted(MongoPersistentProperty property) {
if (property.isAssociation()) {
if (next.getClass().isArray() || next instanceof Iterable) {

List<DBRef> dbRefs = new ArrayList<DBRef>();
for (Object element : asCollection(next)) {
Collection<?> values = asCollection(next);

List<DBRef> dbRefs = new ArrayList<DBRef>(values.size());
for (Object element : values) {
dbRefs.add(writer.toDBRef(element, property));
}

Expand Down Expand Up @@ -264,11 +266,14 @@ private static Collection<?> asCollection(@Nullable Object source) {

if (source instanceof Iterable) {

List<Object> result = new ArrayList<Object>();
if(source instanceof Collection) {
return new ArrayList<>((Collection<?>) source);
}

List<Object> result = new ArrayList<>();
for (Object element : (Iterable<?>) source) {
result.add(element);
}

return result;
}

Expand Down