Skip to content

Commit

Permalink
reduce allocations for searching query index (#925)
Browse files Browse the repository at this point in the history
Iterate the matches list using size/get rather than the
foreach loop which allocates an iterator. This can often
be a hotspot for searching.
  • Loading branch information
brharrington authored Dec 9, 2021
1 parent e66da35 commit 04d126d
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2014-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spectator.atlas;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;

import java.util.ArrayList;
import java.util.List;

@State(Scope.Thread)
public class ListIteration {

private List<Integer> data;

@Setup
public void setup() {
data = new ArrayList<>(100);
for (int i = 0; i < 100; ++i) {
data.add(i);
}
}

@Benchmark
public void forEach(Blackhole bh) {
for (Integer i : data) {
bh.consume(i);
}
}

@Benchmark
public void forUsingGet(Blackhole bh) {
int n = data.size();
for (int i = 0; i < n; ++i) {
bh.consume(data.get(i));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,11 @@ private void forEachMatch(Id tags, int i, Consumer<T> consumer) {
otherChecksCache.put(v, tmp);
}
} else {
for (QueryIndex<T> idx : otherMatches) {
idx.forEachMatch(tags, i + 1, consumer);
// Enhanced for loop typically results in iterator being allocated. Using
// size/get avoids the allocation and has better throughput.
int n = otherMatches.size();
for (int p = 0; p < n; ++p) {
otherMatches.get(p).forEachMatch(tags, i + 1, consumer);
}
}
} else if (cmp > 0) {
Expand Down

0 comments on commit 04d126d

Please sign in to comment.