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

What causes the form to be submitted when the text input is changed?

I'm puzzled by the behavior of this code snippet that triggers form submission when the input value changes: <form> <input type="text" onchange="submit();"> </form> Typically, I would expect something along t ...

What is the best way to pass dynamic values to a service constructor from a component?

After days of attempting to grasp 'the Angular paradigm', I still find myself struggling to understand something about services that are not singletons. It seems impossible for me to pass a runtime-determined value to a service constructor, as I ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

How do I use props to enable and conceal elements like lists, buttons, and images?

Check out this unique component: <ReusedHeader H1headerGray="text here... " H2headerRed="text2 here ! " pheader="p1" getStarted="button text1" hrefab="button url 1" whatWeDo="button text ...

Tips for creating a website with an integrated, easy-to-use editing tool

Recently, I designed a website for a friend who isn't well-versed in HTML/CSS/JavaScript. He specifically requested that the site be custom made instead of using a web creator. Now, he needs to have the ability to make changes to the site without nee ...

Oops! The system encountered a problem while trying to identify the value `Han` for the property `Script

I'm attempting to extract Chinese characters from a string. According to this particular answer, the following code snippet should work: const nonChinese = /[^\p{Script=Han}]/gimu; const text = "asdP asfasf这些年asfagg 我开源的 几 ...

Modify the names of the array variables

I am currently working with JSON data that consists of an array of blog categories, all represented by category id numbers. I am uncertain about how to create a new array that will translate these id numbers into their corresponding category names. Essen ...

no visible text displayed within an input-label field

Currently, I have started working on a multi-step form that is designed to be very simple and clean. However, I am facing an issue where nothing is being displayed when I click on the next arrow. I am puzzled as to why it's not even displaying the te ...

Animation on React child component disappears when re-rendered

My React application utilizes Material UI with a component (let's call it DateSelector) as shown below, slightly altered for demonstration purposes. Material UI provides animations for clicks and interactions within its components. An interesting obs ...

Sending Emails with AngularJS

Exploring AngularJs has been a delightful experience for me, and I recently stumbled upon a fantastic plugin for Angular called angular-http-auth. This plugin allows you to seamlessly integrate an identification system. Does anyone know of a similar resou ...

Ways to integrate PHP MySQL with NodeJS and SocketIO

Currently, I am working on developing a chat application. I have successfully implemented features like creating accounts, logging in, selecting, viewing, and more using PHP MySQL. Now, I am venturing into the Instant Messaging aspect by utilizing NodeJS a ...

trigger a label click when a button is clicked

I am in need of assistance with simulating a label click when a button is clicked. I attempted to make the label the same size as the button so that when the button is clicked, it would check my checkbox. I then tried using JavaScript to simulate the label ...

Tips for reformatting table row data into multiple rows for mobile screens using ng-repeat in Angular

Just started using Angular JS and I have some data available: var aUsers=[{'name':'sachin','runs':20000},{'name':'dravid','runs':15000},{'name':'ganguly','runs':1800 ...

Mastering the art of seamless navigation within a single page through the magic of

I have two HTML pages: "Login.html" and "index.html". Instead of a normal href linking, I want the user to navigate to "index.html" when they click on the login button. Furthermore, I want the index page to be displayed within the codes of login.html, cre ...

Can an Updatepanel control be added to a webpage using Javascript or JQuery?

I'm currently working on a project that involves allowing users to drag icons representing user controls onto a web page. For the desired functionality, these user controls must be contained within an updatepanel (or a similar AJAX-enabled frame) so ...

Steps to create a conditional AJAX request triggered by the onbeforeload event depending on the value of a variable

My website script tracks user login status in real time using "onbeforeunload", ajax, and logout.php. This method updates the MySQL database with a value of 1 or 0 to indicate if a user is logged in. Unlike monitoring cookies, this approach allows accurate ...

Axios: Exception handling does not involve entering the catch method

Implementing a function to adjust a contract name involves making an axios request to the backend API using a specific ID. Upon each execution, a sweetalert prompt is displayed. axios({ url: '/api/contract/' + id, method: 'put ...

After utilizing the function, the forward and back arrows are no longer visible

After setting up my slideshow, I encountered an issue where clicking the next or previous buttons caused them to shrink down and turn into small grey boxes. Has anyone experienced this before? This relates to PHP/HTML if ($_SERVER['REQUEST_METHOD&ap ...

Is it necessary to use callbacks when using mongoose's findbyid with express to retrieve an object from the database? Are callbacks still important in modern JavaScript frameworks?

I'm currently exploring the express local library tutorial on MDN docs and wanted to try out returning an object without relying on a callback method. When I provide the request object parameter for the id to the findById mongoose method like this va ...