Skip to content

Commit 661985c

Browse files
Gaspard Petitjyemin
andcommitted
Adding BsonDocument constructor that allocates an LinkedHashMap with known capacity
JAVA-3613 Signed-off-by: Gaspard Petit <[email protected]> Co-authored-by: Jeff Yemin <[email protected]>
1 parent 11f2fcb commit 661985c

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

bson/src/main/org/bson/BsonDocument.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
public class BsonDocument extends BsonValue implements Map<String, BsonValue>, Cloneable, Bson, Serializable {
5050
private static final long serialVersionUID = 1L;
5151

52-
private final Map<String, BsonValue> map = new LinkedHashMap<String, BsonValue>();
52+
private final Map<String, BsonValue> map;
5353

5454
/**
5555
* Parses a string in MongoDB Extended JSON format to a {@code BsonDocument}
@@ -69,6 +69,7 @@ public static BsonDocument parse(final String json) {
6969
* @param bsonElements a list of {@code BsonElement}
7070
*/
7171
public BsonDocument(final List<BsonElement> bsonElements) {
72+
this(bsonElements.size());
7273
for (BsonElement cur : bsonElements) {
7374
put(cur.getName(), cur.getValue());
7475
}
@@ -81,13 +82,26 @@ public BsonDocument(final List<BsonElement> bsonElements) {
8182
* @param value the value
8283
*/
8384
public BsonDocument(final String key, final BsonValue value) {
85+
this();
8486
put(key, value);
8587
}
8688

89+
/**
90+
* Construct an empty document with the specified initial capacity.
91+
*
92+
* @param initialCapacity the initial capacity
93+
* @throws IllegalArgumentException if the initial capacity is negative
94+
* @since 4.3
95+
*/
96+
public BsonDocument(final int initialCapacity) {
97+
map = new LinkedHashMap<String, BsonValue>(initialCapacity);
98+
}
99+
87100
/**
88101
* Construct an empty document.
89102
*/
90103
public BsonDocument() {
104+
map = new LinkedHashMap<String, BsonValue>();
91105
}
92106

93107
@Override
@@ -844,7 +858,7 @@ public String toString() {
844858

845859
@Override
846860
public BsonDocument clone() {
847-
BsonDocument to = new BsonDocument();
861+
BsonDocument to = new BsonDocument(this.size());
848862
for (Entry<String, BsonValue> cur : entrySet()) {
849863
switch (cur.getValue().getBsonType()) {
850864
case DOCUMENT:

0 commit comments

Comments
 (0)