P5() instance inside p5.Vector?

Hi there. Recently I tried optimising a project I have and I noticed something strange. The p5.Vector() object contains an instance of p5()… the whole p5() object
Inside the src code I found this

p5.Vector = function Vector() {
  let x, y, z;
  // This is how it comes in with createVector()
  if (arguments[0] instanceof p5) {
    // save reference to p5 if passed in
    this.p5 = arguments[0];
    x = arguments[1][0] || 0;
    y = arguments[1][1] || 0;
    z = arguments[1][2] || 0;
    // This is what we'll get with new p5.Vector()
  } else {
    x = arguments[0] || 0;
    y = arguments[1] || 0;
    z = arguments[2] || 0;

Fair enough, maybe for some functionality you would need an instance of p5 inside the Vector(). But my Vectors were created without the first argument being a p5(), but the instance is still there! Demo here

The size of a p5() object is 202 bytes, which seems like a lot of extra memory for each Vector(). Is there a real need for this? I find it odd that I can

1 Like

Variables & properties don’t store an entire object but only hold its reference value (a.K.a. pointer or memory address).

By itself, a property holding a reference won’t increase its object’s size much but just a tiny bit enough to store the memory address reference.

Some p5.Vector methods takes p5’s angleMode() into consideration:

1 Like

Wouldn’t that be true only if p5() was some kind of a singleton?
Check this out

A variable or property can hold 1 value only.
If there’s more than 1 p5 running, a p5.Vector can only refer to 1 of them.


I got it, thank you! Since p5’s memory reference is never modified, in p5.Vector() there is just a reference to it, not an instance.