Allocating memory for JavaScript data types

In my quest to maximize the efficiency of a mobile app I am currently developing, I am curious to find out which data types consume the least amount of memory (keeping in mind that this could differ depending on the browser):

  • object pointers
  • boolean literals
  • number literals
  • string literals

Out of these options, which is expected to occupy the smallest memory space?

Answer №1

Regarding V8:

For Boolean, number, string, null, and void 0 literals in V8, they only take a constant 4/8 bytes of memory for the pointer or immediate integer value embedded in the pointer. There is no heap allocation for these as a string literal will just be internalized. However, exceptions can occur with big integers or doubles which may require boxing with additional bytes. In optimized code, local doubles can remain unboxed in registers or stack, or an array exclusively containing doubles may store them unboxed.

To see the generated code snippet, click here:

function weird(d) {
    var a = "foo";
    var b = "bar";
    var c = "quz";

    if( d ) {
        sideEffects(a, b, c);
    }
}

The pointers to the strings are hard-coded in this example, avoiding any allocation.

Object identities typically require 12/24 bytes for plain objects, 16/32 bytes for arrays, and 32/72 bytes for functions (plus additional bytes if a context object needs allocation). To avoid heap allocation here, bleeding edge V8 along with function inlining is necessary.

Consider the following example:

function arr() {
    return [1,2,3]
}

The values 1,2,3 share a copy-on-write array but unique identity objects need to be allocated. Returning an array from an upper scope can prevent frequent identity allocations. For a simpler alternative, check out this code snippet.

If you encounter memory issues with JS, dynamic function creation could be the culprit. Hoist functions to a level where they don't need recreation to improve performance. Opt for static functions whenever possible.

Excessive memory usage matters in JavaScript as it is traced by garbage collector affecting performance. Run the following snippet with tracing options to observe:

var l = 1024 * 1024 * 2
var a = new Array(l);

for( var i = 0, len = a.length; i < len; ++i ) {
    a[i] = function(){};
}

Compare with using a static function instead:

var l = 1024 * 1024 * 2
var a = new Array(l);
var fn = function(){};

for( var i = 0, len = a.length; i < len; ++i ) {
    a[i] = fn;
}

Answer №2

When we talk about something being "literal," it refers to code itself, even if it's not in string form, which makes it a more intricate type of data and therefore requires more space compared to simple values.

In theory, boolean values could potentially take up the smallest amount of space since they can fit into a single bit. However, it's usually not optimized by most engines. If you really want to ensure this optimization, you may need to manually manipulate typed arrays.

Ultimately, performance is all about practicality, and the best way to understand it is through continuous testing. As we are aware, there is no one-size-fits-all answer that works across all browsers and versions.

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

Errors occur when dealing with higher order functions, such as the "map is

Struggling with higher order functions in JavaScript - I keep running into the error 'map is undefined'. Anyone able to offer some assistance? function mapper(f) { return function(a) { return map(a, f); }; } var increment = function(x) { re ...

Generating a container DIV with loops and ng-class in AngularJS

Currently, I am working on developing a dynamic timeline using AngularJS. To populate my timeline, I have successfully configured the data fetching from a JSON file. You can see what I have accomplished so far on PLNKR: http://plnkr.co/edit/avRkVJNJMs4Ig5m ...

Error encountered in Typescript: SyntaxError due to an unexpected token 'export' appearing

In my React project, I encountered the need to share models (Typescript interfaces in this case) across 3 separate Typescript projects. To address this, I decided to utilize bit.env and imported all my models to https://bit.dev/model/index/~code, which wor ...

Looking for a substitute for a promise within Array.map or a loop?

Seeking guidance on resolving a specific issue. The upload component I'm working with allows for multiple file uploads, resulting in the onDrop function returning both accepted and rejected files (based on extension and size). Among the accepted file ...

Using Firebase Firestore to fetch an array field from a particular document and then leveraging those array values for mapping other documents

In my database, I have user and group collections. Each document in the user collection corresponds to a user UID and contains an array field called "userGroups" which lists the groups that user belongs to, with each group being identified by the group&apo ...

Having issues retrieving a JSON array in PHP with the json_decode function

Can someone assist me with passing and returning an array to a PHP script? I have successfully tested the json_encode portion, but I am facing issues with the json_decode on the PHP side. Javascript scid_list = []; $('.filter_on').each ...

What's the best way to use JavaScript to obtain the width of a 'css-pixel' based on a media query?

While there have been discussions on how to determine device sizes using media queries like Twitter Bootstrap, I am looking for a reliable way to achieve the same output using JavaScript. Specifically, I want to get the CSS media query pixel number rather ...

What is the best way to eliminate backslash escaping from a JavaScript variable?

I am working with a variable called x. var x = "<div class=\\\"abcdef\\\">"; The value of x is <div class=\"abcdef\"> However, I want it to be <div class="abcdef"> Can someone help me unescape ...

Eliminating an index from a JSON array using Typescript

I'm working with a JSON array/model that is structured as follows: var jsonArray = [0] [1] ... [x] [anotherArray][0] [1] ... [e] My goal is to extract only the arrays from [0] to [x] and save them into their ...

My method for updating form input properties involves switching the disable attribute from "false" to "true" and vice versa

I have a form that uses Ajax to submit data. Once the user submits the form, the text is updated to indicate that the data was sent successfully, and then the form is displayed with the fields filled out. I want to display the form but prevent users from r ...

Having trouble getting the Random Function to function correctly in Discord.js

I'm working on a piece of code that generates a random value to select two different values from two separate arrays. Every time I run it, however, the result seems to be the same and not truly random. I'm not sure where I went wrong with this. I ...

Guide to altering JSON using Javascript

https://github.com/smelukov/loftschool-example i am currently working on my project in this environment. I have created a friends.json file in the main folder. friends.json { "name": "John", "lastName": & ...

Can the discriminator be preprocessed in a zod discriminated union?

Is it possible to convert string formatted numbers to numbers before using a value in z.discriminatedUnion? Here is an example code snippet: import { z } from "zod"; const BrushColorEnum = z.enum( ["BLUE_SILVER", "GREEN_SILVER&q ...

Warning from Vue: Steer clear of directly changing a prop as it will be replaced whenever the parent component undergoes re-rendering

I've been diving into Vue.js, but I'm encountering an issue. Every time I try to click on the "edit age" or "change my name" button, I get the following error message. [Vue warn]: Avoid mutating a prop directly because the value will be overwrit ...

Issue encountered when attempting to make a global call to an asynchronous function: "The use of 'await' is restricted to async functions and the top level bodies of modules."

As I embark on solving this issue, I want to point out that while there are similar questions on SO based on the title, upon close examination, they seem more intricate than my specific situation. The explanations provided in those threads do not quite ali ...

implementing a JSON array of integers within an Angular application

I am trying to import a JSON array of integers into scope.data in order to use it for creating D3 bars. However, I am facing issues as the array is not being utilized properly by D3 bars even though it is displayed when using {{data}} in the HTML. Can so ...

SharePoint 2013 only allows the first AJAX request to work successfully, except when in Edit Mode

I am facing a challenge of making two AJAX requests simultaneously on a SharePoint page. One request originates from the current site, while the other comes from a team site. When I use different URLs (/events) and (/travel), each one works fine when use ...

What is the best way to set up a function to automatically execute on a specific date and time

I am facing a challenge with my website where users can send themselves messages at a chosen date and time. However, I am unsure how to trigger the message delivery at the specified time. While I am aware of CronJobs, they seem more suitable for recurring ...

Coming back from the setState callback

In my code, I have a scenario where the Parent component is calling a function from the Child component using refs. Within the Child component function, there is a this.setState method with a callback function embedded in it. handleSaveProject = async () ...

Using Angular, implementing conditional statements within a for loop

I am currently working on a project where I have an array being looped inside a tag, using the target="_blank" attribute. The issue is that one of the elements in the array should not have this target="_blank" attribute. What would be the best course of ...