I'm newbie Java learner. I'm trying to understand how can I write efficient codes in terms of both performance and readability. At this point arrays have been a puzzle for me. Six primitive tests are below. Their first three and second three return almost same times. Please explain what is going on.
String s= "";
int[] Array1=new int[100000];
Long startingTime=System.nanoTime();
for (int i = 0; i < Array1.length; i++) {
s+=i;
}
System.out.println("time : " + (System.nanoTime()-startingTime));
String s= "";
int length=100000;
Long startingTime=System.nanoTime();
for (int i = 0; i < length; i++) {
s+=i;
}
System.out.println("time : " + (System.nanoTime()-startingTime));
String s= "";
int length1=50000;
int length2=50000;
Long startingTime=System.nanoTime();
for (int i = 0; i < length1+length2; i++) {
s+=i;
}
System.out.println("time : " + (System.nanoTime()-startingTime));
public class Test3Length {
static class Foo {
int mSplat = 0;
}
public static void main(String[] args) {
int twentyMillions = 20000000;
Foo[] mArray = new Foo[twentyMillions];
for (int i = 0; i < mArray.length; i++) {
mArray[i] = new Foo();
}
int sum = 0;
Long startingTime = System.nanoTime();
for (int i = 0; i < mArray.length; ++i) {
sum += mArray[i].mSplat;
}
System.out.println("time : " + (System.nanoTime() - startingTime));
}
}
public class Test4Length {
static class Foo {
int mSplat = 0;
}
public static void main(String[] args) {
int twentyMillions = 20000000;
Foo[] mArray = new Foo[twentyMillions];
for (int i = 0; i < mArray.length; i++) {
mArray[i] = new Foo();
}
int sum = 0;
Long startingTime = System.nanoTime();
for (int i = 0; i < twentyMillions; ++i) {
sum += mArray[i].mSplat;
}
System.out.println("time : " + (System.nanoTime() - startingTime));
}
}
public class Test5Length {
static class Foo {
int mSplat = 0;
}
public static void main(String[] args) {
int twentyMillions = 20000000;
Foo[] mArray = new Foo[twentyMillions];
for (int i = 0; i < mArray.length; i++) {
mArray[i] = new Foo();
}
int sum = 0;
Long startingTime = System.nanoTime();
for (Foo a : mArray) {
sum += a.mSplat;
}
System.out.println("time : " + (System.nanoTime() - startingTime));
}
}
First question, would I prefer to int length in for-loop condition rather than array.length?
Second question, would I prefer a foreach loop rather than for-loop unless array is collection?
"I'm newbie Java learner.", I assumed that not to be the case.