How can you optimize the storage of keys in JS objects?

Just pondering over this scenario:

Consider a line definition like the one below, where start and end are both points.

let ln = {
    s: {x:0, y:0},
    e: {x:0, y:0},
    o: 'vertical'
}

Now imagine having a vast array of lines, how can we save space? We could replace the orientation value 'vertical' with an Enum. But is there a way to reduce the key names without compromising readability? For example, replacing orientation with o, but then it may not be immediately clear what that key signifies.

Share your thoughts!

Answer №1

Modern Javascript Engines are highly optimized when it comes to memory usage. Techniques such as internal key lookups and string de-duplication ensure that the length of key names has minimal impact on memory consumption.

To illustrate this, I conducted an experiment where I stored 1 million records in two arrays - one with long key names and the other with short key names. Surprisingly, both arrays consumed approximately 147 bytes per item. Even using a constant for the `vertical` key made little difference in memory usage.

If reducing memory overhead is a priority, TypedArrays could be a viable solution, although they may require more complex handling. By utilizing getters and setters, you might be able to bring down the memory footprint to around 33 bytes per record, comprised of 4 doubles and 1 byte.

However, before diving into optimization efforts, it's important to assess whether such optimizations are truly necessary. Premature optimization in Javascript can often lead to wasted time and resources.

I conducted these memory tests using NodeJs, which leverages Chrome's Javascript engine for execution.

For those interested in exploring how memory is impacted by different data structures, I provided a sample code snippet below that can be run in NodeJs:

const oused = process.memoryUsage().heapUsed;

const values = [];
for (let l = 0; l < 1000000; l += 1) {
    values.push({
        start: { x: 0, y: 0 },
        end: { x: 0, y: 0 },
        orientation: "vertical",
    });
}

console.log(process.memoryUsage().heapUsed - oused);

Answer №2

Check out this example of a line that manages to strike a perfect balance between usability and memory efficiency. By encoding the data positions into the type, it eliminates the need for any string identifiers. Additionally, it utilizes standard arrays since there was no specific size mentioned for the cartesian coordinate plane, ruling out bounded containers like TypedArray:

TS Playground

type Point = [x: number, y: number];

type Line = [a: Point, b: Point];
const line: Line = [[0, 0], [0, 2]];

// Achieving better memory efficiency with 2 fewer arrays per line:
type CompactLine = [...a: Point, ...b: Point];
const compactLine: CompactLine = [0, 0, 0, 2];

Answer №3

To enhance your code, I recommend creating a mapping of shortened keys to their full form and utilizing this map alongside your object. By having the object keys as map keys and their full forms as values, you can easily access and manipulate them.

const keyMap = new Map()
const object = {
  o: 4
} // 'o' represents orientation
keyMap.set("o", "orientation")
const mapKeys = Array.from(keyMap.keys())
const readableObj = {}
mapKeys.forEach(key => {
  const readableKey = keyMap.get(key)
  readableObj[readableKey] = object[key]
})
console.log(object)
console.log(readableObj)

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

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...

Issue alert before running tests on component that includes a Material UI Tooltip

This is a follow-up regarding an issue on the Material-UI GitHub page. You can find more information here. Within my Registration component, there is a button that is initially disabled and should only be enabled after accepting terms and conditions by ch ...

Executing a single command using Yargs triggers the execution of multiple other commands simultaneously

I've been diving into learning nodejs and yargs, and I decided to apply my knowledge by creating a command-line based note-taking app. The structure of my project involves two files: app.js and utils.js. When I run app.js, it imports the functions fr ...

Removing values in javascript for checkboxes that are not selected

Here is the JavaScript Code : var clinicalStat; var id; var val; var clinicalVals; $(":checkbox").click(function() { //alert(" you checked"); if ($(this).is(':checked')) { var checked1 = $(this).val(); //Inital value of check ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

What methods can I use to get my kahoot botter to produce unpredictable answers?

After attempting to create a kahoot botter using the updated kahoot.js library, I came across this code snippet that supposedly answers random questions: const Kahoot = require("kahoot.js-updated"); var kahoots = [] for (var i = 0; i < bot_cou ...

What is the best way to display recently added information?

I'm curious about why the newly added data isn't showing up in the template, even though it does appear when using console.log (check out ViewPost.vue). After adding a new post, this is the result: result.png. Does anyone know how to fix this? ...

What is the best way to transfer data from an Ajax function to a controller action?

I have a button in my view that triggers a jQuery Ajax function, with parameters fetched from my model <input type="button" value="Run Check" onclick="runCheck('@actionItem.StepID', '@Model.Client.DatabaseConnectionString', '@M ...

Using Angular 2 to execute an interface while making an HTTP GET request

I've managed to successfully retrieve and display data from a JSON object using *ngFor in Angular. However, I am struggling with applying an interface to the retrieved data. This is the content of my interface file: import {Offer} from './offer ...

Having trouble retrieving data from redux toolkit using typescript

I've been diving into the world of Typescript by building a simple todo app using React, Redux-toolkit, and Typescript. One issue I encountered is when trying to access data from the store with useSelector. The retrieved object contains the desired va ...

Using NextJs to create a permanent redirect from the www version of a site to the non

I have developed a website using Nextjs (version 12.1.4). To enhance the SEO of my site, I want to create a permanent redirect from the www version to the non-www version. Typically, this can be achieved easily using nginx or an .htaccess file with apache. ...

I am interested in utilizing props to send a variable to the view

Looking for assistance with passing the variable tmp_sell to my view. Here is the code: <p @tmp_sell="getTmpSell" >?</p> <input ref="q_subtotal" placeholder="Subtotal" @tmp_sell="getTmpSell" i ...

Ways to retrieve the text of the <Label> element without relying on the "id" attribute

I have a challenge in extracting text enclosed within the `Label` tag. My knowledge of Javascript and JQuery is limited, so I require guidance on accomplishing this task. Currently, I am attempting to use code that I found on a stackoverflow post titled ge ...

Implement JQuery to include a screensaver on your website

My website in asp.net c# displays the performance of a specific process on an LCD TV screen. The data is refreshed every 15 seconds using the code below: <div id="InfoTop"> <table width="100%" cellpadding="0" cellspacing="0"> ...

Creating a dynamic feature to add a row at the bottom of a table

I am currently working with JavaScript in the context of an AngularJS application, attempting to insert a row at the bottom of a table that shows the total sum of a specific column. Here is the code snippet I am using: var table = document.querySelecto ...

Custom options titled MUI Palette - The property 'primary' is not found in the 'TypeBackground' type

I am currently working on expanding the MUI palette to include my own custom properties. Here is the code I have been using: declare module '@mui/material/styles' { interface Palette { border: Palette['primary'] background: Pa ...

Transferring Composite Data Structures from JavaScript to a WCF RESTful Service

Below are the code snippets: 1. The intricate object: [DataContract] public class NewUser { [DataMember(Name = "Email")] public string Email { get; set; } [DataMember(Name = "FirstName")] public string FirstName { get; set; } [DataMem ...

Tips for presenting random images from an assortment of pictures on a webpage

I'm looking to enhance my website by adding a unique feature - a dynamic banner that showcases various images from a specific picture pool. However, I'm unsure of how to find the right resources or documentation for this. Can you provide any guid ...

Is there a similar function in PHP to creating an array with a specified number of elements in JavaScript using "new Array(number)"?

While attempting to convert a basic Javascript function into PHP, I encountered a variable declared as var Variable = new Array (13). In PHP, variables are typically declared like this: $variable = array() But what does the "13" in new Array(13) signify? ...