Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use delete to to save memory in JavaScript?

Tags:

javascript

Confused on which one of these two is the better approach with respect to saving memory while using JavaScript objects Here is the first approach,

var dates_1 = ["Wed, 04 Jun 2014 08:19:49 -0700","Wed, 07 Jun 2014 08:19:49 -0700","Wed, 04 Jun 2014 06:19:49 -0700"]

var dates2_2 = ["Mon, 04 Jun 2014 08:19:49 -0700","Fri, 04 Jun 2014 08:19:49 -0700","Wed, 04 Jun 2015 08:19:49 -0700"]
var d1,d2,status;
for(var i=0;i<3;i++){
   d1= new Date(dates_1[i]);
   d2 = new Date(dates_2[i]);
   status = (d1>d2)?1:0 ;

Here is the second approach

var d1,d2,status;
for(var i=0;i<3;i++){
   d1= new Date(dates_1[i]);
   d2 = new Date(dates_2[i]);
   status = (d1>d2)?1:0 ;
   delete d1;
   delete d2;

Here,i want to know whether use of delete after every iteration help save any memory or memory leakage ?? or is it safe to just re-assign the values in every iteration without the need for deleting the date object ???

like image 743
Karthic Rao Avatar asked Mar 22 '26 13:03

Karthic Rao


1 Answers

I want to know whether use of delete after every iteration help save any memory or memory leakage

No. JavaScript has automatic memory management. The garbage collector reclaims unused memory automatically, you don't need to do anything.

Moreover, the purpose of the delete operator is not to free memory. It is there to remove (undefine) object properties.

Please read through the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

like image 54
Tomalak Avatar answered Mar 25 '26 02:03

Tomalak