Search code examples
javaobjectprimitive

Is it more expensive to swap objects or primitives in java?


Say I have an array of some comparable objects. For convenience, think Integer. But really it could be some made up data type such as Car or Stuff. Say further that I need to find the extremum. Is it cheaper to swap the indices? the objects? or it does not matter? In other words is example A or example B cheaper

Example A

int least = 0;
for(int i=1; i<objects.length;i++)
  if(objects[i].isLessThan(objects[least)) least= i;

Example B

Stuff least = objects[0];
for(int i=1; i<objects.length;i++)
  if(objects[i].isLessThan(objects[least)) least= objects[i];

Solution

  • It should be the same. If you hadn't done an access to objects[i] first to perform the comparison, then latency introduced because of memory access outside CPU caches could be an issue, but since you already accessed objects[i], this is not likely to be a problem.

    In really large arrays, greater than the page size of the cache, swapping the objects may be faster since you don't need to retrieve objects[least] for every comparison, but this is conjecture.