简体   繁体   中英

How to check memory allocation for a javascript variable

var test = [{a:1,b:2}];

test.value = test;

For the above code, I would like to see how much memory occupied by browser. Is there any side effects in performance (Since test variable is used recursively). I have created an example function from gist but getting Maximum stack calls exceeded. I am just curious to understand the problems of using iterative approach.

I know we can modify above code to make it non-recursive as below:

var test = [{a:1,b:2}];

test.value = [...test];

JS always takes assignments from objects as memory references, there is a lot of ways to only copy the object's value.

This is my favorite one

test.value = Object.assign({}, test);

More generic

object_copy = Object.assign({}, object_origin)

What that code does is merge the original object's value into a new one that we initializate as a empty object {}

Try chrome memory profile snapshot

I just wrote a small code to check the amount of memory allocation during your operation and recorded memory allocation using chrome devtool.

Here is the code that I've wrote:

 <HTML> <body> <button onclick="startTest()">Start Test</button> </body> <script> function startTest() { var test = [{a:1,b:2}]; test.value = test; } </script> </html>

When the button clicked the startTest() function runs.

So I started recording the memory allocation and pressed the Start Test button, and here is the result: 结果

The thin blue line in the picture shows that the memory allocated for the variable test and deallocated by the garbage collector very soon. this means that there is no recursion or any memory allocation problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM