freeing memory in three.js

前端 未结 1 1678
孤街浪徒
孤街浪徒 2020-12-17 02:06

my application loads a lot of meshes. to get rid of old meshes i try to dispose them. but the memory is never being freed.

am i missing something ?

my simpl

相关标签:
1条回答
  • 2020-12-17 02:26

    Probably a typo, but if it isn't: screne.remove(mymesh[j]); should be scene.remove(mymesh[j]);

    Other than that: rember (or find out) how JS manages the memory. Its garbage collector is a sweep-and-clean GC. It flags objects that aren't being referenced anywhere and then cleans them next time the GC kicks in:

    for(var j=0;j<mymesh.length;j++)
    {
        mymesh[j].geometry.dispose();
        mymesh[j].material.dispose();
        scene.remove(mymesh[j]);
    }
    

    The mymesh array still contains references to the mesh objects you are attemting to free. The GC sees this referenec, and therefore refrains from flagging these objects. Reassign, delete, either the entire array of those specific keys you no longer need:

    for(var j=0;j<mymesh.length;j++)
    {
        mymesh[j].geometry.dispose();
        mymesh[j].material.dispose();//don't know if you need these, even
        scene.remove(mymesh[j]);
        mymesh[j] = undefined;//or
        delete(mymesh[j]);
    }
    //or simply:
    mymesh = undefined;//or some other value
    

    That allows the memory to be freed, unless another variable remains in scope that references some or all of these objects, too.
    As an asside:

    mymesh=Array();
    

    Is bad code on many levels. JS functions that begin with an UpperCase are constructors, and should be called usign the new keyword, though most constructors (especially the native objects) shoul be called as little as possibe.
    Their behaviour can be unpredictable, and there's often a shorter way to write the code:

    mymesh = [];//an array literal
    //example of werird behaviour:
    mymesh = new Array(10);//[undefined, undefined, undefined....]
    mymesh = [10];
    mymesh = new Array('10');//['10']
    mymesh = new Array(1.2);//RangeError
    var o = new Object(123);//returns new Nuber
    o = new Object('something');//new String
    o = new Object(false);//new Boolean
    o = new Object('foo', 'bar');//new String('foo')!!!
    o = {foo: 'bar'};//<-- this is soooo much easier
    
    0 讨论(0)
提交回复
热议问题