2

如果您在 javascript 中取消使用过的对象,您是否会保存可能的愚蠢垃圾收集?

例如。

如果您在 javascript 中遍历某些用户:

var users = [
    { FirstName: "Chris", LastName: "Pearson" },
    { FirstName: "Kate", LastName: "Johnson" },
    { FirstName: "Josh", LastName: "Sutherland" },
    { FirstName: "John", LastName: "Ronald" },
    { FirstName: "Steve", LastName: "Pinkerton" }
];

// Do something with the data, perhaps put it in a table

users = null;

现在是否值得取消该列表?是否有人在性能提升背后有一些科学依据,或者是否浪费时间等?

有时很难向人们解释为什么你以某种方式做某事,我知道它在很多场合保存了我的培根,当然,C++,但是在 javascript 中,是否有任何实验来确定它在 javascript 中是否值得?找到一个我可以信任的 sizeof 函数,这让我哭了......如果有人已经做过这种实验,我会很感激看到你想出了什么!

4

1 回答 1

1

这取决于实际情况。例如,这里没有用:

function putUsersInTable(){
    var users = [
        { FirstName: "Chris", LastName: "Pearson" },
        { FirstName: "Kate", LastName: "Johnson" },
        { FirstName: "Josh", LastName: "Sutherland" },
        { FirstName: "John", LastName: "Ronald" },
        { FirstName: "Steve", LastName: "Pinkerton" }
    ];

    // Do something with the data

    users = null; // Useless, the data could be GC'd anyways
}

在这里,它将允许数据在其他情况下不能被 GC 处理:

function putUsersInTable(){
    var users = [
        { FirstName: "Chris", LastName: "Pearson" },
        { FirstName: "Kate", LastName: "Johnson" },
        { FirstName: "Josh", LastName: "Sutherland" },
        { FirstName: "John", LastName: "Ronald" },
        { FirstName: "Steve", LastName: "Pinkerton" }
    ];

    // Do something with the data

    // This could be an event hander in the DOM or any global variable
    outsidethisscope = function(){
        // This anonymous function has access to users,
        // But doesn't necessarily make use of it
        console.log('Hi');
    }

    users = null; // Removes the only reference to that array, 
                  // allowing it to be GC'd
}
于 2013-08-07T16:26:33.427 回答