1.9 Static vs. Non-Static Functions
vihren-milev opened this issue · comments
Hi Daniel,
This is a great book. Thanks for publishing it.
I was going through the first chapter while writing my own code in Java and noticed something rather inefficient in "1.9 Static vs. Non-Static Functions".
The problem is that these static methods create new instances of PVector every time you call them, which could happen 60 time per second when you animate a moving object and a lot more frequently if you have a complex scene. These temporary objects would soon have to be discarded and there would be a lot of work for the Garbage collector.
As an alternative I would recommend using a copyFrom method similar to this:
PVector copyFrom(PVector v) {
x = v.x;
y = v.y;
return this;
}
That method can be combined with using a temporary vector that is reused over and over without having to instantiate new objects. For example:
class MyAnimation
{
PVector v;
PVector u;
PVector tmp;
public MyAnimation()
{
v = new PVector(0,0);
u = new PVector(4,5);
tmp = new PVector(0,0);
}
void update()
{
tmp.copyFrom(u);
tmp.add(v);
// At this point you have the sum of u and v in tmp
// while the original two vectors remain unchanged
}
}
Hope this helps,
Vihren
Thanks for this suggestion. I've addressed this a bit in 6.4. You can also use set()
instead of your own copyFrom()
function.