Which is optimal?

前端 未结 8 534
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 21:23

Is declaring a variable inside a loop is good or declaring on the fly optimal in Java.Also is there any performance cost involved while declaring inside the loop?

eg

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 21:51

    In Clean Code, Robert C. Martin advises Java coders to declare variables as close as possible to where they are to be used. Variables should not have greater scope than necessary. Having the declaration of a variable close to where it's used helps give the reader type and initialization information. Don't concern yourself too much with performance because the JVM is pretty good at optimizing these things. Instead focus on readability.

    BTW: If you're using Java 5 or greater, you can significantly trim up your code example using the following new-for-Java-5 features:

    • foreach construct
    • generics
    • autoboxing

    I've refactored your example to use the aforementioned new features.

    List list = new ArrayList();
    
    // populate list
    
    for (int value : list) {
        System.out.println("value is " + value);
    }
    

提交回复
热议问题