Is the garbage collector called after [removed] re

2019-08-05 04:34发布

问题:

say I have the javascript:

/*getAttribute is mootools method for retrieving a named attribute*/
var companyNumber = button.getAttribute('data-company-number');

var payPoint = button.getAttribute('data-pay-point');

window.location = '/Payslip/ListPayslips/?companyNumber=' + companyNumber + '&payPoint=' + payPoint

delete payPoint;//is this necessary?
delete companyNumber;//is this necessary?

Would the delete lines be necessary? And would they even get called?

回答1:

To answer the first question, yes. Everything is garbage on unload (unload fired on refresh, redirect or close).

To answer the second question, the deletes will not be hit after the redirect. The JS engine will stop there and fire unload etc.

As for the discussion around memory management and explicit variable deletion, here are some considerations:

Good memory management can become important when developing larger web apps that are left open in browser for long periods of time, especially when the target client browsers can be older or on slower machines or mobile devices.

In these cases, where you declare variables to hold temporary information, particularly large objects, you may choose to delete these to free them up for garbage collection. It is my opinion that you should avoid new declarations if they are not necessary and re-use objects where you can - but perhaps not at the expense of readability ;)

To add to 'Corey Ogburn's point, delete itself does not free memory, but disconnects a variable from it's value. It is this that frees the variable for garbage collection.



回答2:

No its not necessary, after the redirect all variables and instances will be deleted.



回答3:

Yes, you lose all the variables if the redirect loads in the current frame/document. The best way to handle this is to create a couple of divs and any redirects need to be loaded in the other div. For instance, you could have a header and main div. Your JS can now reside in the page and any redirects should be loaded into the main div. That way you are preserving state.

An alternative is to use the HTML5 local/session storage.

EDIT: Your second question which is at the bottom regarding delete. No, delete is not necessary. Others have responded with links and reasons why.