Author of "
for real loop performance optimization
" proposes five kinds of optimization strategies to enhance the performance of the for loop, this time in which we drive small cycles nested loop optimization base on a cycle, with the Map efficiently to optimize query performance double for circulation.
If the number of set elements small cycles and a cycle of M and N, respectively, the number of cycles For double loop is N * M, with M and N increase, increasing impact on performance. Therefore, we consider further optimized. With the following code to simulate the performance of tests in both cases:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class forUpdate {
public static void main(String[] args) {
// for (int i = 0; i < 10000; i += 10) {
// loopGivenNum(i);
// }
for (int i = 10000; i < 100000; i += 10000) {
loopGivenNum (i);
}
System.out.println("----- done -----");
}
private static void loopGivenNum(int i) {
List<String> smallLoop = getLoopList(i);
List<String> bigLoop = getLoopList(2 * i);
long doByForTimes = doByFor(bigLoop, smallLoop);
long doByMapTimes = doByMap(bigLoop, smallLoop);
System.out.println("size " + i + ": " + doByForTimes + "," + doByMapTimes);
}
/**
* Get the loop variable
* @Param size loop variable number of elements
* /
Private static List <String> getLoopList ( int size) {
List<String> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(String.valueOf(i));
}
return list;
}
private static long doByFor(List<String> bigLoop, List<String> smallLoop) {
long startTime = System.currentTimeMillis();
for (String str1 : smallLoop) {
for (String str2 : bigLoop) {
if (str1.equals(str2)) {
continue;
}
}
}
return System.currentTimeMillis() - startTime;
}
/**
* Use Map Optimization
* @Param bigLoop
* @param smallLoop
*/
private static long doByMap(List<String> bigLoop, List<String> smallLoop) {
long startTime = System.currentTimeMillis();
// 转换成map
Map<String, String> loopMap = bigLoop.stream().collect(Collectors.toMap(k -> k, Function.identity()));
System.out.println(loopMap.size());
for (String str1 : smallLoop) {
if (loopMap.containsKey(str1)) {
continue;
}
}
return System.currentTimeMillis() - startTime;
}
}
Output:
size 10000: 756,97
size 20000: 3091,8
size 30000: 4342,7
size 40000: 8848,7
size 50000: 16317,7
size 60000: 31652,7
size 70000: 37078,7
由此可见,数据量越大嵌套For循环执行时间越长,而使用Map后,纵使数据量增长到了20w,执行时间也维持在7ms左右。数据量小的时候,执行结果就不再贴出来了。
结论:使用Map优化后的方法执行的效率比嵌套循环提高了很多很多。