How synchronous AJAX call could cause memory leak?

后端 未结 5 1101
野的像风
野的像风 2021-01-31 03:21

I understand this general advice given against the use of synchronous ajax calls, because the synchronous calls block the UI rendering.

The other reason generally given

5条回答
  •  故里飘歌
    2021-01-31 03:58

    Sync XHR block thread execution and all objects in function execution stack of this thread from GC.

    E.g.:

    function (b) { 
      var a = ;
       a and b
      sync XHR
    }
    

    Variables a and b are blocked here (and whole stack too). So, if GC started working then sync XHR has blocked stack, all stack variables will be marked as "survived GC" and be moved from early heap to the more persistent. And a tone of objects that should not survive even the single GC will live many Garbage Collections and even references from these object will survive GC.

    About claims stack blocks GC, and that object marked as long-live objects: see section Conservative Garbage Collection in Clawing Our Way Back To Precision. Also, "marked" objects GCed after the usual heap is GCed, and usually only if there is still need to free more memory (as collecting marked-and-sweeped objs takes more time).

    UPDATE: Is it really a leak, not just early-heap ineffective solution? There are several things to consider.

    • How long these object will be locked after request is finished?
    • Sync XHR can block stack for a unlimited amount of time, XHR has no timeout property (in all non-IE browsers), network problems are not rare.
    • How much UI elements are locked? If it block 20M of memory for just 1 sec == 200k lead in a 2min. Consider many background tabs.
    • Consider case when single sync blocks tone of resources and browser goes to swap file
    • When another event tries to alter DOM in may be blocked by sync XHR, another thread is blocked (and whole it's stack too)
    • If user will repeat the actions that lead to the sync XHR, the whole browser window will be locked. Browsers uses max=2 thread to handle window events.
    • Even without blocking this consumes lots of OS and browser internal resources: thread, critical section resources, UI resources, DOM ... Imagine that your can open (due to memory problem) 10 tabs with sites that use sync XHR and 100 tabs with sites that use async XHR. Is not this memory leak.

提交回复
热议问题