Javascript force GC collection? / Forcefully free object?

后端 未结 3 489
不知归路
不知归路 2020-12-14 01:29

I have a js function for playing any given sound using the Audio interface (creating a new instance for every call).

This works quite well, until about the 32nd call

相关标签:
3条回答
  • 2020-12-14 02:12

    Just deleting and setting it to null didn't work for me either, so I made a workaround.

    I got it working for more than one sound at the same time. To release the instances, every sound needs to be an Object Tag. Dynamically, append every Object Tag (sound) to a Div. To release the instance, dynamically remove the Object Tag (sound) from the Div.

    I guess this works because a browser typically implements each tag as some kind of object. So, when I delete a tag, the internal object gets deleted and releases any resources associated with it.

    <!--HTML: This will contains object sounds-->
    <Div id="sounds"></Div>
    
    //Javacript, using jQuery
    //Create and play an MP3
    var id_event = 1234; //Keep and incrementing a counter might do, I use an Event Id from my app.
    var objSound = "<object width='1' height='1' id='AUDIOIE" + id_event 
            + " type='application/x-oleobject'  AND_MORE_PARAMS_TO_PLAY_A_MP3"
            + "/>";
    $(objSound).appendTo('#sounds');
    

    For complete object params go here.

    //To Stop an MP3 and release it instance.
    $('#AUDIOIE' + id_event).empty().remove();
    
    0 讨论(0)
  • 2020-12-14 02:27

    This is not an exhaustive answer, but to the question "Is there any way to force the chrome js engine to do garbage collection?", a chromium.org guy replied:

    In general, no, by design. For testing purposes there is a flag you can pass on the command line to enable a javascript command "window.gc()" to force garbage collection.

    --js-flags '--expose_gc'


    UPDATE: However, as @plash noted in a comment below, this flag will only work in debug builds.

    0 讨论(0)
  • 2020-12-14 02:28

    I see at least one (or two) flaws:

    snd = new Audio(url);
    

    has no var in front of it, so snd is assigned to the global scope. That's usually not what you want: it clutters the global name space and if another script (e.g., an extension) incidentally uses snd, things will be a mess.

    And that's also why

    delete snd;
    

    doesn't work: you can't delete global variables:

    When declared variables and functions become properties of a Variable object — either Activation object (for Function code), or Global object (for Global code), these properties are created with DontDelete attribute.

    So, use

    var snd = new Audio(url);
    

    instead. BTW, you can't force the JavaScript engine to do garbage collection.

    0 讨论(0)
提交回复
热议问题