我应该在for-each循环中初始化数组?

use*_*856 3 java foreach loops

以下是否会产生不必要的内存使用

    String[] words = text.split(" ");
    for (String s : words)
    {...}
Run Code Online (Sandbox Code Playgroud)

或者text.split(" ")每次循环重复时都会调用以下内容

    for (String s : text.split(" "))
    {...}
Run Code Online (Sandbox Code Playgroud)

哪种方式更可取?

das*_*ght 6

There are pluses to each way of writing your loop:

  • The first way is more debuggable: you can set a breakpoint on the for, and inspect words
  • The second way avoids introducing a name words into the namespace, so you can use the name elsewhere.

As far as performance and readability go, both ways are equally good: the split will be called once before the start of the loop, so there are no performance or memory usage consequences to using the second code snippet.

  • http://ideone.com/Msmnxu证明split()只会被调用一次 (2认同)