지금까지 사용하던 for 루프를 더 빠르게 할 수 있다고?
반복 구문에서의 속도는?
for (int loop = 0; loop < list.size(); loop++)int listSize = list.size();
for (int loop = 0; loop < listSize; loop++)ArrayList<String> list = new ArrayList<String>();
…
for (String str : list)@State(Scope.Thread)
@BenchmarkMode({Mode.AverageTime})
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class ForLoop {
int LOOP_COUNT = 100000;
List<Integer> list;
@Setup
public void setUp() {
list = new ArrayList<>(LOOP_COUNT);
for (int loop = 0; loop < LOOP_COUNT; loop++) {
list.add(loop);
}
}
@Benchmark
public void traditionalForLoop() {
int listSize = list.size();
for (int loop = 0; loop < listSize; loop++) {
resultProcess(list.get(loop));
}
}
@Benchmark
public void traditionalSizeForLoop() {
for (int loop = 0; loop < list.size(); loop++) {
resultProcess(list.get(loop));
}
}
@Benchmark
public void timeForEachLoop() {
for (Integer loop : list) {
resultProcess(loop);
}
}
@Benchmark
public void timeForEachLoopJava8() {
list.forEach(this::resultProcess);
}
int current;
public void resultProcess(int result) {
current = result;
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(ForLoop.class.getSimpleName())
.warmupIterations(3)
.measurementIterations(5)
.forks(1)
.build();
new Runner(opt).run();
}
}반복 구문에서의 필요 없는 반복
Last updated