3

Would the following create unnecessary memory usage

    String[] words = text.split(" ");
    for (String s : words)
    {...}

Or would the following call text.split(" ") every time the loop is repeated

    for (String s : text.split(" "))
    {...}

Which way would be more preferable?

2
  • This sounds like coding convention question and the answer is quite subjective. Personally, I prefer the first way. Commented Nov 21, 2012 at 2:53
  • Both solutions use a similar amount of memory. Commented Nov 21, 2012 at 3:03

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There is no difference in memory usage either
1

Since, there is no difference in terms of performance I think:

String[] words = text.split(" ");
for (String s : words)
{...}

should be used because you can still use the words generated by text.split(" ") for further data manipulation. In the second approach, you can only the words inside the loop.

Comments

0

In the following code getList() is only called once. So I think there is no differences performance-wise about the 2 ways you asked.

class Test {

    static int[] list = {1,2,3,4,5};

    static int[] getList() {
        System.out.println("getList executed");
        return list;
    }

    public static void main(String[] args) {
        for(int n: getList()) {
            System.out.println("n = "+n);
        }
    }
}

Output:

getList executed
n = 1
n = 2
n = 3
n = 4
n = 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.