1

I had a question regarding the following code. I was creating a nested object and I wanted to create it in one short, concise line. I got the idea from this answer here. I'm not planning on using this code for production either. I am being warned that temp 'might' be a leak. This is simply an example I was able to generate. I do understand that newSeasons and temp are being assigned to the same object in memory, that is why all this is possible.

Is this in fact creating a memory leak?

The line in question is:

var newSeasons = temp = {}; temp[yr] = data;

You can test the code here.

function parseData (yr, stat, data) {

    // The way I've been taught
    var oldSeasons = {};
    oldSeasons[yr] = data;
    console.log('The way Ive been taught\n');
    console.log(oldSeasons);


    console.log('\n****************************\n');


    // Experimental way
    var newSeasons = temp = {}; temp[yr] = data;
    console.log('Experimental way');
    console.log(newSeasons);
}

var data = {
    Pos: '1B',
    Age: '33',
    G: '116',
    stat:'batting',
    yr: '2005',
    H:'89',
    R: '42',
    RBI: '48'
};

parseData(data.yr,data.stat,data);
Community
  • 1
  • 1
Fabian Buentello
  • 532
  • 1
  • 4
  • 16

1 Answers1

4

Since you do not declare temp as var temp, you are in fact assigning to window.temp, i.e. to a global variable (assuming we're talking about JS in the browser). The object will not be garbage collected when it's no more needed, unless you explicitely delete the global reference or reassign it.

Edit : This is not a "memory leak" per se : every time you call the function, you're reusing the same global reference, so there is no risk of gradual locking of available space with useless data. However, it constitutes a suboptimal use of resources.

ttzn
  • 2,543
  • 22
  • 26
  • 2
    You're 100% correct, I wouldn't call it a "leak" but it's in class of errors called "accidental global". Because it stays around it will take up memory until the page is reloaded or if it's set to another value. – thomasfuchs Jul 19 '15 at 17:20
  • @Amine, Thank you for that answer! I didn't even see that. So by declaring `temp` with `newSeasons`, I prevent the creation of a global variable? `var newSeasons,temp; newSeasons = temp = {}; temp[yr] = data;` – Fabian Buentello Jul 19 '15 at 17:25
  • @FabianBuentello Indeed that's what happens. When you do that you declare a local variable that won't be accessible once the function block is left, causing the object it holds to be freed. – ttzn Jul 19 '15 at 17:30
  • @thomasfuchs thanks for your comment. I thought about it and it's true that the memory consumption resulting from these errors is bounded by the size of the code (and the number and intensity of mistakes), rather than increasing over time (a true "leak"). But is there even a consensual definition of the concept ? – ttzn Jul 19 '15 at 17:36