Update Optimization (new references vs querying)

Working on optimizing my update() functions in my scripts. I cam across a situation that i am not sure what to do. Here is my existing code inside of my update() function:


let v = this.entity.rigidbody.linearVelocity;
if (v.x < -speedLimit){
    v.set(-speedLimit, v.y, v.z);
    this.entity.rigidbody.linearVelocity = v;
if (v.x > speedLimit){
    v.set(speedLimit, v.y, v.z);
    this.entity.rigidbody.linearVelocity = v;
this.entity.rigidbody.linearVelocity = v;   

Is it better from an optimization standpoint to initialize my variable v or should i just changed every instance of v to this.entity.rigidbody.linearVelocity. This seems like a a lot of work to get the linear velocity of my entities rigidbody. Is this solution faster?


if (this.entity.rigidbody.linearVelocity.x < -speedLimit){
    this.entity.rigidbody.linearVelocity.set(-speedLimit, v.y, v.z);
if (this.entity.rigidbody.linearVelocity.x > speedLimit){
    this.entity.rigidbody.linearVelocity.set(speedLimit, v.y, v.z);

Thanks for your input,

linearVelocity is a set/get property that doesn’t trigger the logic unless you set the whole property so the optmized code won’t work.

See engine source: https://github.com/playcanvas/engine/blob/main/src/framework/components/rigid-body/component.js#L297

Okay thanks for the info - what about for setting. I have in a different update function

let currentPosition = this.sprite.getPosition();
  let myPosition = this.entity.getPosition();
  let lerpX = pc.math.lerp(currentPosition.x, myPosition.x, 0.3);
  let lerpY = pc.math.lerp(currentPosition.y, myPosition.y , 0.3);

do i need to define “currentPosition” and “myPosition” or is it faster just to do

let lerpX = pc.math.lerp(this.sprite.getPosition().x, this.entity.getPosition().x, 0.3);
let lerpY = pc.math.lerp(this.sprite.getPosition().y, this.entity.getPosition().y , 0.3);

Is it faster to allocate the value of the this.sprite.getPosition() to a variable? Or is it just betterr to do option #2

There’s no difference here performance wise really.

The first option is SLIGHTLY faster as you aren’t calling getPosition() multiple times and that has a small cost because under the hood there are few more functions being called

Okay cool thanks for the feedback