Home >Web Front-end >JS Tutorial >How can I determine the approximate size of a JavaScript object in memory?
Determining the Size of a JavaScript Object
Introduction
Estimating the memory usage of a JavaScript object can be a challenging task. In this article, we will explore a comprehensive method to determine the approximate size of an object in JavaScript, inspired by a recent inquiry on getting the size of a JavaScript object.
Addressing the Problem
Consider the following JavaScript code that defines two functions, Marks and Student, and instantiates a new Student object:
function Marks() { this.maxMarks = 100; } function Student() { this.firstName = "firstName"; this.lastName = "lastName"; this.marks = new Marks(); } var stud = new Student();
Estimating Object Size
JavaScript lacks a built-in function similar to the sizeof() operator in C . However, we can devise a custom function to estimate the size of the stud object:
function roughSizeOfObject(object) { const objectList = []; const stack = [object]; let bytes = 0; while (stack.length) { const value = stack.pop(); switch (typeof value) { case 'boolean': bytes += 4; break; case 'string': bytes += value.length * 2; break; case 'number': bytes += 8; break; case 'object': if (!objectList.includes(value)) { objectList.push(value); for (const prop in value) { if (value.hasOwnProperty(prop)) { stack.push(value[prop]); } } } break; } } return bytes; }
This function traverses the object recursively, taking into account the size of primitive values (4 bytes for boolean, 8 bytes for number) and the length of strings in bytes (multiplying by 2). It also maintains an object list to prevent infinite recursion.
Conclusion
Using this function, you can approximate the size of any given JavaScript object, including arrays and custom objects. This method can be useful for optimizing memory usage, especially in performance-critical applications. While it provides an estimate rather than an exact value, it offers a valuable insight into the memory footprint of objects in JavaScript.
The above is the detailed content of How can I determine the approximate size of a JavaScript object in memory?. For more information, please follow other related articles on the PHP Chinese website!