Home > Software design >  Constant variable in global scope or in repeated function
Constant variable in global scope or in repeated function

Time:05-04

I'm building a virtual space with Three.js, integrating 3D assets and spatial sound, so it can be quite performance-challenging. I have a function that is called at each frame (each 1/60 second), and I was wondering where to put the constant variables, for it to spend as little resources as it could.

I'm thinking I should better put it in the global scope, so it won't be assigned again at each frame. But I've learned I should avoid "polluting" the global scope as much as I can, and this variable is required only in that given function.

So, should I put it in the global scope, therefore polluting it a little ? Are re-assigning it each time and reading it from the global scope the same, performance-wise ?

Here is the function to provide some insight, the constant variable is EASING_FACTOR :

function easeTransition(current, old) {
  const EASING_FACTOR = 100;
  let result = {};
  for (const arg in current) {
    const diff = current[arg] - old[arg];
    result[arg] = old[arg]   diff / EASING_FACTOR;
  }

  return result;
}

Thanks!

CodePudding user response:

const EASING_FACTOR = 100;
const EASING_FACTOR_INVERSE = 1/EASING_FACTOR

function easeTransition(current, old) {
  let result = {};
  for (const arg in current) {
    const diff = current[arg] - old[arg];
    result[arg] = old[arg]   diff * EASING_FACTOR_INVERSE;
  }

  return result;
}

Divisions are slower than multiplications, so it would make sense to compute the inverse once and then do thousands of multiplications instead of divisions.

Other patterns should help you avoid polluting the global scope. I'm actually not sure about the terminology here (what kind of modules etc) but if this code is in one file, you would only export the easeTransition function, thus your constants wouldn't actually be global.

If you want to try this "manually" you would use an IIFE:

const easeTransition = (function(){
  const EASING_FACTOR = 100;
  return function _easeTransition(current, old) {
    let result = {};
    for (const arg in current) {
      const diff = current[arg] - old[arg];
      result[arg] = old[arg]   diff / EASING_FACTOR;
    }
    return result;
  }
})() //<- this invokes it "immediately" 

const EASING_FACTOR is now in a "closure" and the only thing you expose is the inner function.

  • Related