可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to know the size occupied by a JavaScript object.
Take the following function:
function Marks(){ this.maxMarks = 100; } function Student(){ this.firstName = "firstName"; this.lastName = "lastName"; this.marks = new Marks(); }
Now I instantiate the student
:
var stud = new Student();
so that I can do stuff like
stud.firstName = "new Firstname"; alert(stud.firstName); stud.marks.maxMarks = 200;
etc.
Now, the stud
object will occupy some size in memory. It has some data and more objects.
How do I find out how much memory the stud
object occupies? Something like a sizeof()
in JavaScript? It would be really awesome if I could find it out in a single function call like sizeof(stud)
.
I’ve been searching the Internet for months―couldn’t find it (asked in a couple of forums―no replies).
回答1:
I have re-factored the code in my original answer. I have removed the recursion and removed the assumed existence overhead.
function roughSizeOfObject( object ) { var objectList = []; var stack = [ object ]; var bytes = 0; while ( stack.length ) { var value = stack.pop(); if ( typeof value === 'boolean' ) { bytes += 4; } else if ( typeof value === 'string' ) { bytes += value.length * 2; } else if ( typeof value === 'number' ) { bytes += 8; } else if ( typeof value === 'object' && objectList.indexOf( value ) === -1 ) { objectList.push( value ); for( var i in value ) { stack.push( value[ i ] ); } } } return bytes; }
回答2:
The Google Chrome Heap Profiler allows you to inspect object memory use.
You need to be able to locate the object in the trace which can be tricky. If you pin the object to the Window global, it is pretty easy to find from the "Containment" listing mode.
In the attached screenshot, I created an object called "testObj" on the window. I then located in the profiler (after making a recording) and it shows the full size of the object and everything in it under "retained size".
More details on the memory breakdowns.
In the above screenshot, the object shows a retained size of 60. I believe the unit is bytes here.
回答3:
I just wrote this to solve a similar (ish) problem. It doesn't exactly do what you may be looking for, ie it doesn't take into account how the interpreter stores the object.
But, if you are using V8, it should give you a fairly ok approximation as the awesome prototyping and hidden classes lick up most of the overhead.
function roughSizeOfObject( object ) { var objectList = []; var recurse = function( value ) { var bytes = 0; if ( typeof value === 'boolean' ) { bytes = 4; } else if ( typeof value === 'string' ) { bytes = value.length * 2; } else if ( typeof value === 'number' ) { bytes = 8; } else if ( typeof value === 'object' && objectList.indexOf( value ) === -1 ) { objectList[ objectList.length ] = value; for( i in value ) { bytes+= 8; // an assumed existence overhead bytes+= recurse( value[i] ) } } return bytes; } return recurse( object ); }
回答4:
Sometimes I use this to flag really big objects that might be going to the client from the server. It doesn't represent the in memory footprint. It just gets you approximately what it'd cost to send it, or store it.
Also note, it's slow, dev only. But for getting an ballpark answer with one line of code it's been useful for me.
roughObjSize = JSON.stringify(bigObject).length;
回答5:
There is a NPM module to get object sizeof, you can install it with npm install object-sizeof
var sizeof = require('object-sizeof'); // 2B per character, 6 chars total => 12B console.log(sizeof({abc: 'def'})); // 8B for Number => 8B console.log(sizeof(12345); var param = { 'a': 1, 'b': 2, 'c': { 'd': 4 } }; // 4 one two-bytes char strings and 3 eighth-bytes numbers => 32B console.log(sizeof(param));
回答6:
This is a hacky method, but i tried it twice with different numbers and it seems to be consistent.
What you can do is to try and allocate a huge number of objects, like one or two million objects of the kind you want. Put the objects in an array to prevent the garbage collector from releasing them (note that this will add a slight memory overhead because of the array, but i hope this shouldn't matter and besides if you are going to worry about objects being in memory, you store them somewhere). Add an alert before and after the allocation and in each alert check how much memory the Firefox process is taking. Before you open the page with the test, make sure you have a fresh Firefox instance. Open the page, note the memory usage after the "before" alert is shown. Close the alert, wait for the memory to be allocated. Subtract the new memory from the older and divide it by the amount of allocations. Example:
function Marks() { this.maxMarks = 100; } function Student() { this.firstName = "firstName"; this.lastName = "lastName"; this.marks = new Marks(); } var manyObjects = new Array(); alert('before'); for (var i=0; i
I tried this in my computer and the process had 48352K of memory when the "before" alert was shown. After the allocation, Firefox had 440236K of memory. For 2million allocations, this is about 200 bytes for each object.
I tried it again with 1million allocations and the result was similar: 196 bytes per object (i suppose the extra data in 2mill was used for Array).
So, here is a hacky method that might help you. JavaScript doesn't provide a "sizeof" method for a reason: each JavaScript implementaion is different. In Google Chrome for example the same page uses about 66 bytes for each object (judging from the task manager at least).
回答7:
A little late to the party, but here's a slightly more compact solution to the problem:
const typeSizes = { "undefined": () => 0, "boolean": () => 4, "number": () => 8, "string": item => 2 * item.length, "object": item => Object .keys(item || {}) .reduce((total, key) => sizeOf(key) + sizeOf(item[key]) + total, 0) }; const sizeOf = value => typeSizes[typeof value](value);
回答8:
Sorry I could not comment, so I just continue the work from tomwrong. This enhanced version will not count object more than once, thus no infinite loop. Plus, I reckon the key of an object should be also counted, roughly.
function roughSizeOfObject( value, level ) { if(level == undefined) level = 0; var bytes = 0; if ( typeof value === 'boolean' ) { bytes = 4; } else if ( typeof value === 'string' ) { bytes = value.length * 2; } else if ( typeof value === 'number' ) { bytes = 8; } else if ( typeof value === 'object' ) { if(value['__visited__']) return 0; value['__visited__'] = 1; for( i in value ) { bytes += i.length * 2; bytes+= 8; // an assumed existence overhead bytes+= roughSizeOfObject( value[i], 1 ) } } if(level == 0){ clear__visited__(value); } return bytes; } function clear__visited__(value){ if(typeof value == 'object'){ delete value['__visited__']; for(var i in value){ clear__visited__(value[i]); } } } roughSizeOfObject(a);
回答9:
i want to know if my memory reduction efforts actually help in reducing memory
Following up on this comment, here's what you should do: Try to produce a memory problem - Write code that creates all these objects and graudally increase the upper limit until you ran into a problem (Browser crash, Browser freeze or an Out-Of-memory error). Ideally you should repeat this experiment with different browsers and different operating system.
Now there are two options: option 1 - You didn't succeed in producing the memory problem. Hence, you are worrying for nothing. You don't have a memory issue and your program is fine.
option 2- you did get a memory problem. Now ask yourself whether the limit at which the problem occurred is reasonable (in other words: is it likely that this amount of objects will be created at normal use of your code). If the answer is 'No' then you're fine. Otherwise you now know how many objects your code can create. Rework the algorithm such that it does not breach this limit.
回答10:
This Javascript library sizeof.js
does the same thing. Include it like this
The sizeof function takes an object as a parameter and returns its approximate size in bytes. For example:
// define an object var object = { 'boolean' : true, 'number' : 1, 'string' : 'a', 'array' : [1, 2, 3] }; // determine the size of the object var size = sizeof(object);
The sizeof function can handle objects that contain multiple references to other objects and recursive references.
Originally published here.
回答11:
Having the same problem. I searched on Google and I want to share with stackoverflow community this solution.
Important:
I used the function shared by Yan Qing on github https://gist.github.com/zensh/4975495
function memorySizeOf(obj) { var bytes = 0; function sizeOf(obj) { if(obj !== null && obj !== undefined) { switch(typeof obj) { case 'number': bytes += 8; break; case 'string': bytes += obj.length * 2; break; case 'boolean': bytes += 4; break; case 'object': var objClass = Object.prototype.toString.call(obj).slice(8, -1); if(objClass === 'Object' || objClass === 'Array') { for(var key in obj) { if(!obj.hasOwnProperty(key)) continue; sizeOf(obj[key]); } } else bytes += obj.toString().length * 2; break; } } return bytes; }; function formatByteSize(bytes) { if(bytes
What do you think about it?
回答12:
If your main concern is the memory usage of your Firefox extension, I suggest checking with Mozilla developers.
Mozilla provides on its wiki a list of tools to analyze memory leaks.
回答13:
Chrome developer tools has this functionality. I found this article very helpful and does exactly what you want: https://developers.google.com/chrome-developer-tools/docs/heap-profiling
回答14:
function sizeOf(parent_data, size) { for (var prop in parent_data) { let value = parent_data[prop]; if (typeof value === 'boolean') { size += 4; } else if (typeof value === 'string') { size += value.length * 2; } else if (typeof value === 'number') { size += 8; } else { let oldSize = size; size += sizeOf(value, oldSize) - oldSize; } } return size; } function roughSizeOfObject(object) { let size = 0; for each (let prop in object) { size += sizeOf(prop, 0); } // for.. return size; }
回答15:
Many thanks to everyone that has been working on code for this!
I just wanted to add that I've been looking for exactly the same thing, but in my case it's for managing a cache of processed objects to avoid having to re-parse and process objects from ajax calls that may or may not have been cached by the browser. This is especially useful for objects that require a lot of processing, usually anything that isn't in JSON format, but it can get very costly to keep these things cached in a large project or an app/extension that is left running for a long time.
Anyway, I use it for something something like:
var myCache = { cache: {}, order: [], size: 0, maxSize: 2 * 1024 * 1024, // 2mb add: function(key, object) { // Otherwise add new object var size = this.getObjectSize(object); if (size > this.maxSize) return; // Can't store this object var total = this.size + size; // Check for existing entry, as replacing it will free up space if (typeof(this.cache[key]) !== 'undefined') { for (var i = 0; i this.maxSize) { var entry = this.order.shift(); delete this.cache[entry.key]; total -= entry.size; } this.cache[key] = object; this.order.push({ size: size, key: key }); this.size = total; }, get: function(key) { var value = this.cache[key]; if (typeof(value) !== 'undefined') { // Return this key for longer for (var i = 0; i
It's a simplistic example and may have some errors, but it gives the idea, as you can use it to hold onto static objects (contents won't change) with some degree of intelligence. This can significantly cut down on any expensive processing requirements that the object had to be produced in the first place.
回答16:
回答17:
If you need to programatically check for aprox. size of objects you can also check this library http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/ that I have been able to use for objects size.
Otherwise I suggest to use the Chrome/Firefox Heap Profiler.
回答18:
I believe you forgot to include 'array'.
typeOf : function(value) { var s = typeof value; if (s === 'object') { if (value) { if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function') { s = 'array'; } } else { s = 'null'; } } return s; }, estimateSizeOfObject: function(value, level) { if(undefined === level) level = 0; var bytes = 0; if ('boolean' === typeOf(value)) bytes = 4; else if ('string' === typeOf(value)) bytes = value.length * 2; else if ('number' === typeOf(value)) bytes = 8; else if ('object' === typeOf(value) || 'array' === typeOf(value)) { for(var i in value) { bytes += i.length * 2; bytes+= 8; // an assumed existence overhead bytes+= estimateSizeOfObject(value[i], 1) } } return bytes; }, formatByteSize : function(bytes) { if (bytes
回答19:
I know this is absolutely not the right way to do it, yet it've helped me a few times in the past to get the approx object file size:
Write your object/response to the console or a new tab, copy the results to a new notepad file, save it, and check the file size. The notepad file itself is just a few bytes, so you'll get a fairly accurate object file size.