0

Let's say I have a class

Box(double xi, double yi, double zi, double xf, double yf, double zf)

and I have a method

Box#collides(Box other){
   if(other.xf < xi || other.xi > xf) return false;
   if(other.yf < yi || other.yi > yf) return false;  
   return other.zf >= zi && other.zi <= zf;
}

I then get two boxes. I compare the first

Box(a,b,c,d,e,f)

with .collides() to the other box,

Box(A,B,C,D,E,F)

Will the Box objects still be created? Or will the JVM be smart and use something similar to

static collides(double xi, double yi, double zi, double xf, double yf, double zf, double xi, double oyi, double ozi, double oxf, double oyf, double ozf){
   if(oxf < xi || oxi > xf) return false;
   if(oyf < yi || oyi > yf) return false;  
   return ozf >= zi && ozi <= zf;
}

This might seem like a micro-optimization, but in my case, potentially millions of Boxes are being instantiated.

andrewgazelka
  • 1,746
  • 1
  • 16
  • 26

1 Answers1

1

It may or may not happen. The HotSpot JVM an do this, but only when everything gets inlined in a single method (there are no intra-procedural optimizations other than those converted to inter-procedural by inlining).

It must see the while allocation, the test and the running out-of-scope in a single procedure (after inlining). This may well happen, but there's no guarantee. However, a few million boxes means about a few times 60 megabytes, which is a lot, but allocating a few MB per second is pretty common.

If you want to be sure, provide a method like Box#collides(double xi, double yi, double zi, double xf, double yf, double zf).

maaartinus
  • 44,714
  • 32
  • 161
  • 320