What are the "...toRef" Methods? How Should We Use Them?

To expand a little more on @sebavan and @Deltakosh 's comments

In your question you show ‘toRef’ with only one parameter.

It requires two parameters, the vector to add and a results vector in which the addition is stored.

This (rather implausible) example shows the benefit of ‘toRef’ over the basic

There is a line of points along the x axis and from each point we need to draw a random unit vector. We achieve this for each point A by generating a random point B and forming the unit vector from A to B.

Method 1 - GC (garbage collection) rich

for (var i = 0; i < 10; i++) {
    var A = new BABYLON.Vector3(2 * i, 0, 0);
    var B = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
    B.normalize();
    var C = A.add(B);
    // draw line from A to C

Method 2 -GC light

var A = BABYLON.Vector3.Zero();
var B = BABYLON.Vector3.Zero();
var C = BABYLON.Vector3.Zero();
for (var i = 0; i < 10; i++) {
    A.x = 2 * i;
    B.set(Math.random(), Math.random(), Math.random());
    B.normalize();
    A.addToRef(B, C);
    // draw line from A to C
}
2 Likes