代码定义在循环内和定义在循环外有什么区别呢?这两种方式有什么好坏之分?- public class Test2 {
-
- public static void main(String[] args) {
-
- // 放入10000000的元素
- List<Object> list = new ArrayList<Object>(10000000);
- for(int i = 0; i < 10000000; i++) {
- list.add(i, new Object());
- }
-
- // 做10次循环,求均值
- for(int j = 0; j < 10; j++) {
-
- // 变量在循环内定义
- long t1 = System.currentTimeMillis();
- for(Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
- Object object = iterator.next();
- }
- long t2 = System.currentTimeMillis();
- System.out.println("循环内" + (j + 1) + "次, 时间:" + (t2 - t1) + ";");
-
- // 变量在循环外定义
- t1 = System.currentTimeMillis();
- Object object = null;
- for(Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
- object = iterator.next();
- }
- t2 = System.currentTimeMillis();
- System.out.println("循环外" + (j + 1) + "次, 时间:" + (t2 - t1) + ";");
- }
- }
- }
-
复制代码 |
|