Which is more memory efficient: creating an object with functions defined on it using a function, or creating an instance of a class?

Imagine if I were to create a hypothetical class (this is purely for demonstration purposes)

class X {
  constructor(word, number) {
    this.wordNumberString = word + number;
  }
  saySomething() {
    return `${this.wordNumberString} ${this.wordNumberString}`;
  }
  addAnotherWordNumberString(word, number) {
    this.wordNumberString += word + number;
  }
}

Would developing a function that forms a closure, encapsulating data by defining functions within and returning them:

const generateX = (word, number) => {
  let wordNumberString = word + number;
  const saySomething = () => {
    return `${wordNumberString} ${wordNumberString}`;
  }
  const addAnotherWordNumberString = (word, number) => {
    wordNumberString += word + number;
  }
  return { saySomething, addAnotherWordNumberString };
}

be more efficient in terms of memory usage?

For instance, would

Array(100000).fill(null).map((_, i) => new X(i, new Date() + i*123456))

have greater benefits than:

Array(100000).fill(null).map((_, i) => generateX(i, new Date() + i*123456))

Answer ā„–1

Let's discuss different approaches to programming in JavaScript: using a style with createA or similar is common, while using class A or similar is also popular.

Would [creating different functions each time] be less efficient in terms of memory?

Yes, it would be slightly less efficient due to function objects and closure, but whether this impact is significant depends on other factors as well.

When using the class, function objects for methods are reused by each instance of the class because they are inherited from the prototype:

class A {
  constructor(name, date) {
    this.nameDateString = name + date;
  }
  someMethod() {
    return `${this.nameDateString} ${this.nameDateString}`;
  }
  addAnotherNameDateString(name, date) {
    this.nameDateString += name + date;
  }
}

const a1 = new A("Joe", new Date());
const a2 = new A("Mary", new Date());
console.log(a1.someMethod === a2.someMethod); // true

On the other hand, when using the createA function, different function objects are created every time createA is called:

const createA = (name, date) => {
  let nameDateString = name + date;
  const someMethod = () => {
    return `${nameDateString} ${nameDateString}`;
  }
  const addAnotherNameDateString = (name, date) => {
    nameDateString += name + date;
  }
  return { someMethod, addAnotherNameDateString };
}

const a1 = createA("Joe", new Date());
const a2 = createA("Mary", new Date());

console.log(a1.someMethod === a2.someMethod); // false

Objects created by createA have a larger memory imprint compared to those created by new A as they possess their own copies of function objects.

However, the code underlying these function objects will be reused by any decent JavaScript engine. For instance:

const a1 = createA("Joe", new Date());
const a2 = createA("Mary", new Date());

In this scenario, memory allocation might look something like the following diagram shows...

(For detailed explanation, refer to the original text)

Ultimately, if the memory efficiency is crucial for your application, measure the impact with real code and consider using tools like Memory tab in browser dev tools to monitor memory consumption based on your coding choices.

Answer ā„–2

The efficiency of your code depends on the specific JavaScript engine that is running it. Some engines may be smart enough to recognize that the functions within createA are consistent but with different closures, and optimize accordingly. To determine which approach is best, it is recommended to conduct performance measurements. (As noted in the comments, most modern engines tend to optimize code sufficiently so that the underlying code object is shared among functions even when the closure varies.)

Using a class eliminates the need for the engine to make clever optimizations since the methods belong to the class's prototype. Moreover, using classes aligns more closely with current coding conventions, making it a preferable choice.

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

Ensure that the number is valid using Express Validator in Node.js

One thing that I've noticed when using express validator is the difference between these two code snippets: check('isActive', 'isActive should be either 0 or 1').optional({ checkFalsy : false, nullable : false }).isInt().isIn([0, 1 ...

inside the connect module, the res._renderHeaders function is located

Currently, I am delving into the patch.js file within the connect module. In it, I found some intriguing code snippets: var http = require('http') , res = http.ServerResponse.prototype , setHeader = res.setHeader , _renderHeaders = res._re ...

Changing the .load function based on user input

Can I replace a .load text with one that can be updated by a user using form input or similar method? My goal is to create a code that retrieves data using unique div IDs (specific to each employee) containing information within tables across various HTML ...

Generate a table containing information organized by category

I am looking to create a component Table that groups countries together. Here is my mockup: enter image description here I am struggling to find a solution for this issue. Can someone please assist me? ...

What is the method for eliminating PHP $_SESSION using AJAX?

I am facing an issue with removing an array within a PHP Session variable using AJAX. Here is the process I follow: HTML: <a href="#" onclick="delete_pix(false, '1', false, '1.jpg');">remove</a> JavaScript: functio ...

Displaying the active navigation element in ApyCom JavaScript jQuery menu: tips and tricks

Currently, I am utilizing the jQuery navigation menu from ApyCom. Everything seems to be functioning properly except for one issue. Whenever I click on a different navigation element, I expect that element to remain highlighted in order to indicate to the ...

Guide to obtaining specific top elements from an array using JavaScript

I'm seeking assistance with sorting arrays in JavaScript. Here is an example of a sorted array: mainArray : [25 20 20 20 18 17 17 15 12 12 10 5 5 ] The mainArray may contain duplicate values. A. Dealing with duplicates Based on user input, I need ...

The array value remains unchanged when included in the response

My goal is to send back the "projets" array within an expressJs route after fetching images for each item. However, when I return the response with the updated array, the newly added fields don't seem to be included. Note: When I log the added item, ...

Cross Domain Requests in Internet Explorer: Preflight not being sent

I have come across several similar discussions but none of the solutions provided have worked for me so far. Issue: In our current setup, we have three servers hosting our http-apis - two for testing and one for production. Lately, we have been deployin ...

Troubleshooting Problems Arising from PHP, Ajax, and SQL Integration

I've been encountering an issue that seems simple, but I haven't been able to find a solution specific to my problem in the forums. The problem arises when I try to display a table of hyperlinks, each linked to an AJAX method with an 'oncli ...

Leveraging the replace feature within Selenium IDE

After extracting information from a webpage, I found a string that read "price: $30.00" which I saved as "x." What I really needed was just the numbers - "30.00". I attempted to use x.replace(), but unfortunately it didn't work out. If anyone could as ...

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

What could be causing the lack of animation in W3schools icons?

I've followed the steps provided and even attempted to copy and paste them. However, I'm experiencing an issue where the animation doesn't fully execute. Instead of the bars turning into an X shape, they reset halfway through the animation. ...

How to seamlessly integrate Redux into your React project using create-react-app?

Is it correct to pass a reducer as props when using a rootreducer? This is the content of my rootReducer.js file: import { combineReducers } from 'redux'; import simpleReducer from './simpleReducer'; import messageReducer from '. ...

Hidden Document Scroll Offset

When CSS is used to hide scrollbar html, body { width: 100%; overflow-x: hidden } The above code snippet removes the scroll from the window but triggers it on the body element. To calculate the scroll values in such cases, you can use: pageOffset = ...

How can you show a green check mark next to an input field in AngularJS after inputting valid data?

I am diving into the world of AngularJS and Angular Material with my web application. As a beginner in AngularJS and Angular Material, I need some help. My current task is to display a green checkmark next to an input field only when valid data is entere ...

What are your thoughts on the practice of utilizing the useState hook within a component to send data to its parent component?

I have been working on developing an Input component that can be dynamically used in any page to store input values. The component also includes an attribute called getValue, which allows the parent component to access the input value. In my App.js file, I ...

Discover Vue3's efficient event handling feature that allows you to easily listen to events from dynamically generated child components

I am dynamically creating a Vue component and need to listen to the event it emits. While I know that you can use @eventName in the markup, my component is being created using createApp. const div = document.createElement('div'); this.$refs.logi ...

Displaying images retrieved from firebase on a React.js application

Currently, I am attempting to retrieve images from Firebase storage and then exhibit them in a React component. As a newcomer to React/Javascript, I find it challenging to grasp the asynchronous nature of React/JS. The issue I'm facing is that althoug ...

JavaScript prototypal inheritance concept

During my free time, I like to dabble in JavaScript, but Iā€™m currently struggling with this particular topic. var person = new Person("Bob", "Smith", 52); var teacher = new Teacher("Adam", "Greff", 209); function Humans(firstName, lastName) { this. ...