2014-10-03 42 views
1

以下哪个代码更好,为什么?以下哪个代码更好?

第一种方式:

String[] animals = "lion tiger zebra".split(" "); 
for (String animal : animals) { 
    System.out.println(animal); 
} 

方式二:

for (String animal : "lion tiger zebra".split(" ")) { 
    System.out.println(animal); 
} 

将代码lion tiger zebra".split(" ")循环重复所有的时间或仅在第一时间执行。

+1

“优化”..认真。 [请阅读这些引文。](http://en.wikipedia.org/wiki/Program_optimization#Quotes)。 – user2864740 2014-10-03 16:17:56

+0

无论如何,Java被迫切地评估(禁止短路运算符) - 在这种情况下,这意味着它是执行迭代的“狮子老虎斑马”.split(“”)“的结果。 – user2864740 2014-10-03 16:19:24

+0

第一种方式更好,更具可读性 – user902383 2014-10-03 16:27:09

回答

1

第一种方式将需要内存为该方法的整个执行的变量,或者如果它在一个类中,然后直到类给GC。

第二种方式会在循环执行后留下GC分割字符串的内存。

回答你的问题Will the code lion tiger zebra".split(" ") be executed all the time the loop is repeated or just the first time.

将只进行一次。

1

它没有区别。无论哪种方式,拆分操作只会执行一次。

1

这两段代码几乎没有区别。但是,第一个选项更具可读性,但它们(除非操作过长)才会执行几乎相同的时间。