Declaring Objects

edited January 2016 in Questions about Code


I'm currently reading The Nature of Code and I noticed that in some of the examples PVector is defined in draw. Take Example 1.4:

void setup() {

void draw() {

    PVector mouse = new PVector(mouseX,mouseY);
    PVector center = new PVector(width/2,height/2);

    //Multiplying a vector! The vector is now half its original size (multiplied by 0.5).



I've been using Processing for a while but I'm not a Java expert. I was wondering if the compiler does something to save the PVector because it seems like declaring new ones in each draw frame would be really inefficient.

Generally I layout my sketches like this:

MyObject myObject;
PVector myPVector;

void setup() {
    myObject = new myObject();
    myPVector = new PVector();

void draw() {

In general, is it costly to define objects in draw? I know that I gained a lot of speed in an Android game I made just by replacing ArrayLists with arrays of game objects so I figured it would be.



  • Answer ✓

    It will be more efficient to create the objects in setup and update them in draw, if needed. In your example the PVector center will only change if the sketch window is resized, so won't need changing if the window is not resizable.

  • edited January 2016 Answer ✓

    In general, is it costly to define objects in draw?

    • Performance-wise, it depends on how much time is needed to complete a class' constructor, along w/ other declaration & initialization blocks in it.
    • I'd say PVector is pretty fast. HashMap, normal. But something like Movie is slow.
    • And since Java 6, it's got "Escape Analysis":
    • It doesn't make the instantiation any faster though. But it may spare the GC to deal w/ such object once it's outta scope, by allocating it @ the stack rather than @ the heap memory region.
    • Either way, if we know that we're gonna be using some object over & over, it's a wise move to keep it around rather than creating another 1 non-stop.
    • Both Pvector mouse & center can be declared global and instantiated once.
    • Then reset its own state within draw() by invoking its method set().
    • Also notice that center never changes its state. It's forever the center coords. of the canvas. ;;)

    final PVector mouse = new PVector(), center = new PVector();
    void setup() {
      size(640, 360);
      center.set(width>>1, height>>1);
    void draw() {
      mouse.set(mouseX, mouseY).add(center).mult(.5);
      line(center.x, center.y, mouse.x, mouse.y);

    P.S.: Though an excellent book for computer drawings, it's the worst example for efficiency techniques! :P

Sign In or Register to comment.