Im making a 3D OpenGL LWJGL game and i've replaced a class for 3D float vectors with its generic version, and implemented "clone()" method from "Cloneable". After that, performance drops significally (GC usage went from below 1% to 10%). Here's a code example for vector edition before and after the change:
Before:
public class Vec3f {
public float x, y, z;
...
public Vec3f add(Vec3f v) {
return new Vec3f(x + v.x, y + v.y, z + v.z);
}
public Vec3f addThis(Vec3f v) {
x += v.x;
y += v.y;
z += v.z;
}
}
After:
public abstract class Vec<V extends Vec<V>> implements Cloneable {
private Class<V> klass;
protected float[] coords;
protected Vec(int dim, Class<V> klass) {
this(dim, new float[dim], klass);
}
public V clone() {
try {
V c = klass.newInstance();
c.coords = this.coords.clone();
return c;
}
catch(InstantiationException e1) {}
catch(IllegalAccessException e2) {}
return null;
}
...
public V add(V that) {
V sum = this.clone();
sum.addThis(that);
return sum;
}
public void addThis(V that) {
for (int i = 0; i < coords.length; i++) {
coords[i] += that.coords[i];
}
}
}
public class Vec3 extends Vec<Vec3> {
public Vec3() {
super(3, Vec3.class);
}
}
But it makes no sense at all, as the code actually does the exact same thing.