简体   繁体   English

如何检查 javascript 变量的 memory 分配

[英]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.对于上面的代码,我想看看浏览器占用了多少memory。 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.我从gist创建了一个示例 function 但超出了最大堆栈调用。 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. JS 总是将对象的赋值作为 memory 引用,有很多方法可以只复制对象的值。

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 {}该代码所做的是将原始对象的值合并到一个新对象中,我们将其初始化为空 object {}

Try chrome memory profile snapshot尝试 chrome memory 配置文件快照

I just wrote a small code to check the amount of memory allocation during your operation and recorded memory allocation using chrome devtool.我刚刚写了一个小代码来检查您操作过程中 memory 的分配量,并使用 chrome devtool 记录了 memory 的分配量。

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.当按钮单击时 startTest() function 运行。

So I started recording the memory allocation and pressed the Start Test button, and here is the result:于是我开始记录 memory 分配并按下Start Test按钮,结果如下: 结果

The thin blue line in the picture shows that the memory allocated for the variable test and deallocated by the garbage collector very soon.图片中的蓝色细线显示为变量test分配的 memory 很快被垃圾收集器释放。 this means that there is no recursion or any memory allocation problem.这意味着不存在递归或任何 memory 分配问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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