时间:2022-08-28 09:29:41 | 栏目:JAVA代码 | 点击:次
前言
我们都经常使用一些循环耗时计算的操作,特别是for循环,它是一种重复计算的操作,如果处理不好,耗时就比较大,如果处理书写得当将大大提高效率,下面总结几条for循环的常见优化方式。
首先,我们初始化一个集合 list,如下:
List<String> list = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }
int m = list.size(); for (int i = 0; i < m; i++) { System.out.println(list.get(i)); }
for (int i = 0, n = list.size(); i < n; i++) { System.out.println(list.get(i)); }
for (int i = list.size() - 1; i >= 0; i--) { System.out.println(list.get(i)); }
for (Iterator<String> it = list.iterator(); it.hasNext();) { System.out.println(it.next()); }
for (Object o : list) { System.out.println(o); }
for (int i = 0; i < 10; i++) { for (int j = 0; j < 10000; j++) { } }
原因
//前: int a = 10, b = 11; for (int i = 0; i < 10; i++) { i = i * a * b; } //后: int c = a * b; for (int i = 0; i < 10; i++) { i = i * c; }
反例
for (int i = 0; i < 10; i++) { try { } catch (Exception e) { } }
正例
try { for (int i = 0; i < 10; i++) { } } catch (Exception e) { } catch (Exception e) { } }
正例
try { for (int i = 0; i < 10; i++) { } } catch (Exception e) { }