I tried to find work for each cycle when I make a function call. See the following code,
public static int [] returnArr()
{
int [] a=new int [] {1,2,3,4,5};
return a;
}
public static void main(String[] args)
{
for(int a : returnArr())
{
System.out.println(a);
}
int [] myArr=returnArr();
for(int a : myArr)
{
System.out.println(a);
}
}
In version 1, I call the returnArr () method for each loop, and in version 2 I explicitly call the returnArr () method and assign it to an array, and then repeat it. The result is the same for both scenarios. I would like to know what is more effective and why.
I thought version 2 would be more efficient since I do not call the method at each iteration. But, to my surprise, when I debugged code using version 1, I saw that the method was called only once!
Can someone explain how this works? ? What is more efficient / better when I code complex objects?