I wrote tests to figure out that whether assigning references is slower or equally fast compared with assigning primitive types values, and my result is, assigning references is much slower.
@Test
public void testPassReference(){
long count = 0;
DoublyLinkedNodeNoGetter node1 = linkedList.head;
DoublyLinkedNodeNoGetter[] nodes = new DoublyLinkedNodeNoGetter[2];
nodes[0] = linkedList.head.next;
nodes[1] = linkedList.head.next.next;
while(count++<10000000000l){
node1 = nodes[(int)(count%2)];
}
}
@Test
public void testPassValue(){
long i = 0;
long j = 0;
while(i++<10000000000l){
j = i%2;
}
And the result:
testPassReference: 8s 934ms
testPassValue: 2s 707ms
I am confused because from my understanding, when assign an Object using '=', it means transfer the reference, which is the address, from one object to the other one. Even in the 64 bit system, the reference should be 64 bit in length, which is the length of the primitive type 'long'. Thus why assigning a reference is so slow? What happened during we assign a reference to another?
I would be appreciate for your help! Thank you!
UPDATE:
Thanks for the comments!
There are defects in my test approach. I am still thinking about how to make a fair test for both of them. T.T
So, forget about the test, theoretically is there any difference in the two kinds of assignment?
UPDATE2:
@Test
public void testPassReference(){
long count = 0;
DoublyLinkedNodeNoGetter node1 = linkedList.head;
DoublyLinkedNodeNoGetter[] nodes = new DoublyLinkedNodeNoGetter[2];
nodes[0] = linkedList.head.next;
nodes[1] = linkedList.head.next.next;
while(count++<10000000000l){
node1 = nodes[(int)(count%2)];
}
}
@Test
public void testPassValue(){
long i = 0;
long[] j = {1,2};
long k;
while(i++<10000000000l){
k = j[(int)(i%2)];
}
}
Again I re-designed the tests and now I get similar result. So I think the type of assignments has few effects on the performance of operation.
testPassReference: 9s 5ms
testPassValue: 9s 4ms