Skip to main content

Best method to reduce object allocation in recursive loop

2 replies [Last post]
byhisdeeds
Offline
Joined: 2006-01-06

I have an application where I need to generate multiple vertex coordinates iteratively. Presently I use the following code:

buildTrianglePatch(vertices,txCoords,8,p0,i0,p1,i1,p2,i2);

public void buildTrianglePatch(FloatBuffer vertices, TexCoords texcoords,
int lev, Point.Point3D p0, int i0, Point.Point3D p1,
int i1, Point.Point3D p2, int i2)
{
Point.Point3D p = new Point.Point3D();
int i;

if (lev==0)
{
// write the three vertex coordinates
vertices.put(texcoords.get()).put(texcoords.get())
.put((float)p0.p0).put((float)p0.p1).put((float)p0.p2)
.put(texcoords.get()).put(texcoords.get())
.put((float)p1.p0).put((float)p1.p1).put((float)p1.p2)
.put(texcoords.get()).put(texcoords.get())
.put((float)p2.p0).put((float)p2.p1).put((float)p2.p2);
return;
}

p.p0=0.5*(p1.p0+p2.p0);
p.p1=0.5*(p1.p1+p2.p1);
p.p2=0.5*(p1.p2+p2.p2);
i=(i1+i2)>>1;
lev--;
buildTrianglePatch(h,vertices,texcoords,lev,p,i,p0,i0,p1,i1);
buildTrianglePatch(h,vertices,texcoords,lev,p,i,p2,i2,p0,i0);

return;
}

In profiling my application I see where the repeated allocation of the Point.Point3D object () which is just a wrapper for 3 floating point variables) uses up to a few mega bytes of memory before the gc trips in. I want to get rid of this temporary memory allocation in the loop and was wondering if anyone could say if I used three float variables in place of the object in the looping code
whetehr I would save on memory allocation.

I'm thinking here that there still would be the need to allocate 3 floating point variables for every object at every recursive call of the buildTraingePatch method.

John

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
mbien
Offline
Joined: 2007-04-29

you could allocate your Point once and pass it with every recursion (a little bit hacky because you do not need the parameter as input) or allocate the point as (final and maybe static) class variable and use it in the method (use ThreadLocal if you have multithreading requirements).

swv
Offline
Joined: 2007-05-28

Your only hope as far a I can see is if you're using the 3 points and dont' need the Point. Point3D object for any reason, maybe not using it would reduce memory (if it's a pig with a lot of extra-for-your-purposes state). Other than that I can't think of anything....