Skip to content

Commit 1d62cef

Browse files
etkishakuzen
andauthored
Improved Meter.Id#getTags() performance (#6182)
Avoids allocating an ArrayList for empty Tags, and sizes the ArrayList with new package-private API on Tags to get the size. This avoids the cost of growing the ArrayList or allocating a bigger array than needed. Signed-off-by: etki <[email protected]> Co-authored-by: Tommy Ludwig <[email protected]>
1 parent 7d6d68d commit 1d62cef

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

micrometer-core/src/main/java/io/micrometer/core/instrument/Meter.java

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -281,9 +281,15 @@ public String getName() {
281281
* @return A set of dimensions that allows you to break down the name.
282282
*/
283283
public List<Tag> getTags() {
284-
List<Tag> tags = new ArrayList<>();
285-
this.tags.forEach(tags::add);
286-
return Collections.unmodifiableList(tags);
284+
if (this.tags == Tags.empty()) {
285+
return Collections.emptyList();
286+
}
287+
288+
List<Tag> list = new ArrayList<>(this.tags.size());
289+
for (Tag tag : this.tags) {
290+
list.add(tag);
291+
}
292+
return Collections.unmodifiableList(list);
287293
}
288294

289295
public Iterable<Tag> getTagsAsIterable() {

micrometer-core/src/main/java/io/micrometer/core/instrument/Tags.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,15 @@ public Tags and(@Nullable Iterable<? extends Tag> tags) {
225225
return merge(Tags.of(tags));
226226
}
227227

228+
/**
229+
* Non-public (for now) method to get the size of this, which can be useful in sizing
230+
* a collection where these elements will be copied.
231+
* @return number of unique {@link Tag} instances in this
232+
*/
233+
int size() {
234+
return length;
235+
}
236+
228237
@Override
229238
public Iterator<Tag> iterator() {
230239
return new ArrayIterator();

0 commit comments

Comments
 (0)