Implications of using literals, objects, or classes as arguments in functions that are called multiple times can have

Context

A project I'm working on involves a scenario where a Shape class is triggering a function call SetPosition( x, y ) on a Drawer class. As part of this process, the Drawer class needs to retain the values (x, y) passed through SetPosition.

There could potentially be numerous shapes, resulting in multiple calls being made from a single user interaction.

I am contemplating the memory and garbage collection implications when using objects or classes versus literals for these calls.

Below are the specific details regarding different approaches.

Consistency Across Options

I apologize for utilizing class-like syntax in the code examples below; however, it has no impact on the core question. One can easily substitute the Class syntax with standard JS functions & prototype syntax if needed.

In all the options presented here, the shape class is initialized with a property shapeType that represents a new instance of an existing class ShapeType:

Shape = new Class({

    // Initialization 
    initialize: function() {
        this.shapeType = new ShapeType( 0, 0, 10, 10 );
    }    
});

Option 1 - Using Primitive Values

The Shape class:

Shape = new Class({
    draw: function( drawerInstance ) {
        drawerInstance.setPosition( this.shapeType.x, this.shapeType.y );
    }       
});

The Drawer class:

Drawer = new Class({

    // Initialization 
    initialize: function() {
        this.position = {
            x: 0,
            y: 0
        };
    },

    setPosition: function( x, y ) {
        this.position.x = x;
        this.position.y = y;
    }       
});

Considerations

As far as I understand, there is no memory allocation involved in this option, so there shouldn't be any major concerns - it's pretty straightforward.

Option 2 - Utilizing Object Literals

The Shape class:

Shape = new Class({    
    draw: function( drawerInstance ) {
        drawerInstance.setPosition( { x: this.shapeType.x, y: this.shapeType.y } );
    }       
});

The Drawer class:

Drawer = new Class({

    // Initialization 
    initialize: function() {
        this.position = {
            x: 0,
            y: 0
        };
    },

    setPosition: function( newPosition ) {
        this.position = newPosition;
    }       
});

Considerations

My query revolves around whether by using

drawerInstance.setPosition( { x: this.shapeType.x, y: this.shapeType.y } );

a new object gets created. Moreover, upon executing

this.position = newPosition;

wouldn't the previous object now be subject to garbage collection?

Option 3 - Leveraging Class Instances

The Shape class:

Shape = new Class({    
    draw: function( drawerInstance ) {
        // shapeType.getPosition() returns a new Point( x, y );
        drawerInstance.setPosition( this.shapeType.getPosition() );
    }       
});

The Drawer class:

Drawer = new Class({

    // Initialization 
    initialize: function() {
        this.position = new Point( 0, 0 );
    },

    setPosition: function( newPosition ) {
        this.position = newPosition;
    }       
});

Considerations

Given that getPosition() provides a new point class instance (new Point( x, y )) it clearly indicates memory allocation involvement as illustrated here:

// shapeType.getPosition() returns a new Point( x, y );
drawerInstance.setPosition( this.shapeType.getPosition() );

It's evident that with this line:

this.position = newPosition;

the previous position object (class) would be cleared via garbage collection.

Does this hold any distinctions compared to option 2?

Considering this is the preferred approach for me (given that the Point class offers methods beneficial for other operations within setPosition) would it pose challenges considering the high volume of calls per user action (in contrast to options 1 and 2)?

Answer №1

In my opinion, utilizing object pools can be a highly efficient method for managing memory usage in scenarios like this one. By pre-allocating the required number of objects and reusing them as needed, you can mitigate potential garbage collection issues.

Regarding your query,

The line of code: aRenderer.setTranslate( { x: this.rect.x, y: this.rect.y } );

will instantiate a new object, leading to the previous translate object becoming eligible for garbage collection (assuming there are no other active references).

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

Encountering a data retrieval issue when using the useSWR hook in a project using reactjs

I am trying to retrieve data from the backend using useSWR. However, I have encountered two bugs in the function getDataUseSWR. The errors occur at line 'fetch(url).then': 1: "Expected 0 arguments, but got 1."; 2: "Property 'then' does ...

Steps to refresh your nodejs project after making changes

As a newcomer to nodejs, I find myself constantly restarting the server every time I make changes to my HTML files or when using twig, jade, or ejs template engines. Does anyone have any suggestions on how to see these changes in the browser without having ...

Creating Table Rows on-the-fly

Seeking assistance and guidance from the community, I have modified code from an online tutorial to allow users to dynamically add rows to a table when data is entered in the row above. However, I am facing an issue where I can only insert one additional ...

Is it possible to implement a validation process that prevents the opening of a modal using data-bs-target until all necessary

I am currently using bootstrap version 5.2.3 and I have encountered an issue where the modal opens regardless of validation rules being met or not. I attempted to modify the data-bs-toggle and data-bs-target attributes using Vue.js, but the changes did no ...

The error "req.user is not defined" occurs when accessing it from an Android

I am currently collaborating with an Android developer to create an android app. While my colleague handles the front-end development, I focus on the backend work. Specifically, I have implemented the login and authentication features using node.js, expres ...

quickest method for retrieving a property by name, regardless of its location within the object hierarchy

I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below. Instead of using recursion, I have chosen tree traversal because it cons ...

Tips for retrieving the value of a tag within a modal popup

I am trying to extract the value from an 'a' tag using the code below. <div class="modal fade show" id="myModal" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" style="display: block;"> <div class="modal-d ...

Second attempt at initiating Ajax request fails

My ajax/php structure works perfectly when selecting one image. However, if I click on "selecteer" to perform the same code for the second time, no images are displayed. The "ajax" page loads correctly each time. Here's the setup: Article page: Disp ...

The JSON request was unsuccessful in sending the JSON object to PHP, resulting in an empty var_dump

I am encountering an issue where my $_POST array in PHP is empty when I try to pass a JSON object with an AJAX request on my JavaScript page. Here is the JavaScript code: function send(cat, subcat) { var type = cat.options[cat.selectedIndex].text ...

The requested resource does not have the 'Access-Control-Allow-Origin' header, resulting in a 401 error

I've been working on integrating spell check functionality using the Bing Spell Check API, but I've run into a 401 error. The specific error message is: The requested resource does not have an 'Access-Control-Allow-Origin' header. This ...

The search function in Select2 is not displaying the desired result

I'm encountering an issue with the search functionality when it uses Ajax to load data from a JSON file. For example, if I search for Yemen, the record for Yemen does not get selected or highlighted properly. Here is the complete source code - could ...

Steps for generating random numbers from a set of given numbers

I am faced with a scenario where I need to generate random numbers based on a given set of numbers. For instance, if I have an array num=[23,56,12,22], I would like to obtain a random number from this array. ...

Color-Thief Node plugin reported an issue: "The provided image has not finished loading."

While working in Node/Express, I attempted to utilize the npm package color-thief to extract the dominant color from an image. Unfortunately, it failed with the error message stating that the "image given has not completed loading". The intriguing part is ...

Managing repeated calls to a specific get function in nodejs

Utilizing an Ajax call, I am invoking the following GET function every 10 seconds to monitor the status of various URLs. app.get('/getUrl', function(req, res) { var response = {}; var keyArr = []; var urlData ...

Retrieving a file URL from Sanity within a blocks array

I've been working on a website with Next JS and using Sanity as the CMS. While Sanity has schemas for images, I ran into an issue when trying to handle videos. The documentation recommends using GROQ queries to convert file URLs at the request level, ...

Extracting information from a database (HTML, JavaScript)

I am currently working on a table that receives data from the server using ajax: $.each(data, function(i, item) { $('#MyTable tbody').append("<tr>" +"<td>" +data[i].A+ "</td><td>" +d ...

Apply a border to the navbar when it hovers over a selected element

export const NavBar = () => { return <div className="navbar">this is navbar</div>; }; const Content = () => { return ( <div className="main"> <div className="background"> some content </div> ...

Acquire JSON data structures using Node.js

I've been struggling to find a solution using just keywords - endless scrolling, yet all I can find are tutorials on getting data from JSON structure, rather than getting data structure from JSON. If you're unsure what my end goal is, here are s ...

Turning an array of strings into a multidimensional array

I have a JavaScript string array that I need to convert into a multidimensional array: const names = [ "local://john/doe/blog", "local://jane/smith/portfolio", "as://alexander/wong/resume" ]; The desired output sh ...

How to disable or enable a submit button in jQuery 1.8

Recently, I upgraded from jquery version 1.5.2 to 1.9 and encountered an issue with my disabled buttons not functioning properly. The buttons should become enabled after the form fields are filled out, allowing the user to either remove or save the infor ...