A constant variable either in the global scope or within a frequently used function

I am currently working on a virtual environment using Three.js, where I am incorporating 3D elements and spatial sound. This kind of project can be quite demanding in terms of performance. I have a function that is called every frame (approximately every 1/60th of a second), and I am trying to determine the best placement for constant variables in order to minimize resource usage.

My initial thought was to place the constant variables in the global scope so they do not need to be reassigned with each frame. However, I am aware of the concept of "polluting" the global scope and prefer to avoid it whenever possible. Additionally, these variables are only required within that particular function.

Should I proceed with putting it in the global scope, even though it may slightly clutter it? Is there a difference in performance between re-assigning the variable each time or reading it from the global scope?

Below is the function where the constant variable EASING_FACTOR is used:

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;
}

Thank you!

Answer №1

const EASING_FACTOR = 100;
const EASING_FACTOR_INVERSE = 1/EASING_FACTOR

function smoothTransition(current, previous) {
  let outcome = {};
  for (const item in current) {
    const difference = current[item] - previous[item];
    outcome[item] = previous[item] + difference * EASING_FACTOR_INVERSE;
  }

  return outcome;
}

Instead of using divisions which are slower, it's more efficient to calculate the inverse once and then perform multiple multiplications rather than divisions.

Employing other design patterns can help prevent cluttering the global scope. If this code is contained in a single file, you could export only the smoothTransition function, ensuring that your constants are not truly global.

If you choose to implement this manually, you can use an Immediately Invoked Function Expression (IIFE):

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

Now, the EASING_FACTOR is encapsulated in a closure and only the inner function is exposed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Whenever I attempt to invoke a generic handler through cross-domain using ajax, the data returned turns out to be undefined upon the successful

Whenever I use Ajax to call a generic handler across different domains, the data comes back as undefined in the success callback. function getUserInfo() { currentUser = null; $.ajax({ type: 'GET', ...

Discovering a way to monitor keyup and keydown occurrences in JavaScript on an iPhone

Looking to track keyup/keydown events in JavaScript on iPhone browsers. My goal is to automatically move the focus to the next form element after the user has inputted the maximum number of characters in a text box. ...

Evaluate a program to identify prime numbers

I am currently working on a JavaScript program that utilizes recursion to determine whether an input is a prime number or not. Within my code, I've defined the isPrime function. The base cases are set to return false when x==1 and true for x==2, cons ...

Create geometric shapes on Google Maps version 2

Can anyone guide me on how to draw a polygon on Google Maps with user-input coordinates? I have two input fields for latitude and longitude, and when the user clicks the button, I want the polygon to be drawn. The code I currently have doesn't seem to ...

Unable to process login information with form method post on basic login page

Hi, I've been struggling with a simple login page issue. It works fine with Bootstrap, but I want to switch to Angular Material Design. I've been searching for the problem for about 3-4 hours and can't find anything. I suspect that the form ...

jQuery uploads elements only when the page is initially loaded for the first time

The issue seems to be related to the $(document).ready(function() {}); code block or potential misuse of callbacks. My goal is to execute getTotalMarketCap(), getAllOtherValues(), and getMarketShare() in sequence for an accurate market share calculation. ...

Utilizing dependency injection within an Angular 1 TypeScript application

Seeking assistance with integrating angular-jwt with typescript in my angular1 project. The angular-jwt package was installed using the following command: typings install dt~angular-jwt --global The package is located in typings>globals>angular-jwt ...

Enhance the performance of React code by refactoring it

Having recently started coding in React for a new organization, I find that the code in my component has grown lengthy and the submithandler method is causing multiple array iterations. Is there a way to refactor the code for better performance? The data t ...

What is the process of incorporating a video into a react.js project through the use of the HTML

I'm experiencing an issue where my video player loads, but the video itself does not. Can anyone shed light on why this might be happening? class App extends Component { render() { return ( <div className="App& ...

Using the 'gf' command in Vim to resolve JavaScript modules with a Webpack tilde alias

Recently, I joined a Vue.js project that makes use of the tilde (~) notation in module imports. For example: import WhateverApi from '~/api/whatever'; The project repository is a mix of various files including a Vagrant machine setup, a Laravel ...

Determine the duration/length of an audio file that has been uploaded to a React application

I am working on a React web application built with create-react-app that allows users to upload songs using react-hook-forms. The uploaded songs are then sent to my Node/Express server via axios. I want to implement a feature that calculates the length of ...

What could be the reason for Next.js middleware rewrite not executing two times?

Issue with Next.js Middleware Execution While working on implementing next.js middleware, I encountered a situation where I needed to set up two redirects. One redirect was intended to switch a Desktop URL to a Mobile URL, and the second one aimed to modi ...

"OBJLoader Three.js r74, bringing vibrantly colored elements to your 3

It's a straightforward process, I import my OBJ model that was exported using 3DS Max. I have the intention of coloring a specific section of the Object. During the animation loop, I implement the following: scene.traverse( function( object ) { ...

What steps can be taken to create a progress bar in the input field that spans the entire width of its parent div, reaching

I received assistance from a friend in creating this progress bar. Everything seems to be working well, except for the fact that the progress bar is not extending to the full width of the parent div. The new width after each input tag is entered using Java ...

Is it feasible to manage the HTML content surrounding my information within the Google Maps InfoWindow in ReactJS?

In my Google Maps application, I have an InfoWindow that displays some of my HTML content created in React. return ( <div className="map-tooltip-wrapper"> <div className="map-tooltip-image><img src={image || '& ...

When watching YouTube videos in full screen mode on F11, the IFrame zooms in excessively, causing the video quality to suffer

After using the same code as the website Virtual Vacation, I noticed that they are experiencing the same issue as me. I am considering reaching out to them to inform them about it, but I am struggling to find a solution on my own. Specifically on WINDOWS ...

Exploring various components within Material UI to effectively navigate between them

How can I use Material UI to navigate to a different component? Below is the code for my drawer list: <List> {['POS', 'Stock', 'Send email', 'Drafts'].map((text, index) => ( <List ...

Rounding to Significant Digits: The Mystery of Vanishing Zeros

I am currently working on a JavaScript mathematics package that focuses on rounding to different significant figures (S.F.), but I have encountered a problem that is proving challenging to solve. Before delving into the issue, let me provide some backgrou ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

Looping through Vue with multiple options

Looking for help with Vue2 looping to display multiple options within a select element. We have an object structured like this; sorting = { name: [ 'asc', 'desc' ], price: [ 'cheapest', ...