I work with an array SomeObject[] someObject = new SomeObject[5000];.
Each instance inside this array is unique to each other instance, but, as a statistical expectation, they require the same computational cost. In addition, the standard deviation of the distribution of computational overheads for each is someObject[i]very narrow (each someObject[i]must accept 8- 12each nanosecond, mainly clustering about 10nanoseconds).
I noticed that if I populate this array with an identical instance sharedObject = new SomeObject()and go through SomeObject[], it will be very fast. For instance:
SomeObject sharedObject = new SomeObject();
for(int i = 0; i < 5000 ; ++i) {
someObjects[i] = sharedObject;
}
for(int i = 0; i < 5000 ; ++i) {
someObjects[i].doSomething();
}
But if I fill the array like:
for(int i = 0; i < 5000 ; ++i) {
someObjects[i] = new SomeObject();
}
for(int i = 0; i < 5000 ; ++i) {
someObjects[i].doSomething();
}
someObject 8 , , ( 1 2 ), .
?
someObject .
, new SomeObject(), .
, ( , ):
public class Test2 {
public final double random;
public final Double[] sub;
public Test2(double random) {
this.random = random;
sub = new Double[1000];
for(int i = 0 ; i < 1000 ; ++i) {
sub[i] = Math.random();
}
}
public void doSomething() {
for(int i = 0 ; i < 1000 ; ++i) {
double j = (i - 1000)*5*6/4/4/4*sub[i];
}
}
public static void main(String[] args) {
Test2 testFirst = new Test2(Math.random());
Test2[] testFirstArray = new Test2[10000];
Test2[] testSecondArray = new Test2[10000];
for(int i = 0 ; i < 10000 ; ++i) {
testFirstArray[i] = testFirst;
testSecondArray[i] = new Test2(Math.random());
}
for(int i = 0 ; i < 10000 ; ++i) {
testFirstArray[i].doSomething();
testSecondArray[i].doSomething();
}
double firstTimer = System.nanoTime();
for(int i = 0 ; i < 10000 ; ++i) {
testFirstArray[i].doSomething();
}
System.out.println((System.nanoTime() - firstTimer)/(1000*1000));
double secondTimer = System.nanoTime();
for(int i = 0 ; i < 10000 ; ++i) {
testSecondArray[i].doSomething();
}
System.out.println((System.nanoTime() - secondTimer)/(1000*1000));
}
}