## Javafor循环性能优化实现解析

2020年02月13日 编程语言 ⁄ 共 2769字 ⁄ 字号 评论关闭

1 嵌套循环

private static void bigSmall() { long stratTime = System.nanoTime(); for (int i = 0; i < 10000000; i++) { for (int j = 0; j < 100; j++) { } } long endTime = System.nanoTime(); System.out.println("外大内小耗时：" + (endTime - stratTime)); }

private static void smallBig() { long stratTime = System.nanoTime(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 10000000; j++) { } } long endTime = System.nanoTime(); System.out.println("外小内大耗时：" + (endTime - stratTime)); }

2 循环变量的实例化应放在循环外

private static void smallBigBetter() { long stratTime = System.nanoTime(); int i, j; for (i = 0; i < 100; i++) { for (j = 0; j < 10000000; j++) { } } long endTime = System.nanoTime(); System.out.println("外小内大并且提取出循环内变量耗时：" + (endTime - stratTime)); }

3 提取与循环无关的表达式

private static void calculationInner() { int a = 3; int b = 7; long stratTime = System.nanoTime(); for (int i = 0; i < 10000000; i++) { i = i * a * b; } long endTime = System.nanoTime(); System.out.println("未提取耗时：" + (endTime - stratTime)); }

private static void calculationOuter() { int a = 3; int b = 7; int c = a * b; long stratTime = System.nanoTime(); for (int i = 0; i < 10000000; i++) { i = i * c; } long endTime = System.nanoTime(); System.out.println("已提取耗时：" + (endTime - stratTime)); }

4 消除循环终止判断时的方法调用

stratTime = System.nanoTime(); for (int i = 0; i < list.size(); i++) { } endTime = System.nanoTime(); System.out.println("未优化list耗时："+(endTime - stratTime));

stratTime = System.nanoTime(); int size = list.size(); for (int i = 0; i < size; i++) { } endTime = System.nanoTime(); System.out.println("优化list耗时："+(endTime - stratTime));

5 异常捕获

private static void catchInner() { long stratTime = System.nanoTime(); for (int i = 0; i < 10000000; i++) { try { } catch (Exception e) { } } long endTime = System.nanoTime(); System.out.println("在内部捕获异常耗时：" + (endTime - stratTime)); }

private static void catchOuter() { long stratTime = System.nanoTime(); try { for (int i = 0; i < 10000000; i++) { } } catch (Exception e) { } long endTime = System.nanoTime(); System.out.println("在外部捕获异常耗时：" + (endTime - stratTime)); }