4

I am programming for a memory-constrained device. Hence, I want to avoid allocating any memory.

Obviously, iterating across sets, lists, etc will allocate an iterator and thus allocate memory. So this should be avoided.

Does the native java syntax for iterating across arrays allocate memory?

Object[] array = getArray()
for(Object elem: array){
  //do something
}

(I suppose I could always use the old-fashioned for loop with an index variable.)

4
  • 3
    I wasn't aware that one could disable the JVM garbage-collector. How does anything work in that scenario? Commented Jan 15, 2012 at 14:34
  • ... and more importantly, can that be called Java? Commented Jan 15, 2012 at 14:35
  • You're right, the GC is not completely disabled - we just want to avoid having it run, so I prefer to view it as such. Commented Jan 15, 2012 at 14:38
  • Refer to this question. stackoverflow.com/questions/5369730/java-for-loop-differences Commented Jan 15, 2012 at 14:43

2 Answers 2

6

Nope. In all compilers that I have checked this is implemented by a for loop (0..array.lengh-1).

Note that Java arrays do not implement Iterable. This can be seen, for instance, by the following code:

Object[] arr = new String[100];
Iterable<?> iter = arr;  // Error: 'Type mismatch: 
                         //         cannot convert from Object[] to Iterable<?>'

[UPDATE]

And here is the definite source: https://docs.oracle.com/javase/specs/jls/se13/html/jls-14.html#jls-14.14.2

A for loop such as

for ( VariableModifiersopt Type Identifier: Expression) Statement

has the following meaning when Expression is an array of type T[]:

T[] a = Expression;
for (int i = 0; i < a.length; i++) {
       VariableModifiersopt Type Identifier = a[i];
       Statement
}
Sign up to request clarification or add additional context in comments.

Comments

2

It doesn't allocate new memory. The following foreach loop:

for (type var : array) {
    body-of-loop
}

Is equivalent to this:

for (int i = 0; i < array.length; i++) { 
    type var = array[i];
    body-of-loop
}

As you can see, no additional memory allocation is being made.

2 Comments

To be specific it takes some stak space for type var = array[i] ;)
Well, int i and type var do allocate a bit of stack memory (and a constant value), but no additional heap memory is allocated.

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.