Check if a variable exists - Memory ?

Posted on
  • Hi Espruinos,

    I just searching a proper way to detect if a variable is defined/exists without loosing memory. Yes it's all about memory....

    I tried it in two ways:

     if(variable !==undefined)
    

    and

    if(typeof variable !=='undefined')
    

    Here is the memory loosing code:

    test={};
    
    console.log(process.memory());
    for(i=0;i<1000;i++) {
      if(test['hello'+i]!==undefined)
      {
        console.log('hello'+i+' is defined');
      }
    }
    console.log(process.memory());
    
    Output:
    
    {"free":1780,"usage":20,"total":1800,"hi­story":5,"stackEndAddress":536909512,"fl­ash_start":134217728,"flash_binary_end":­134432224,"flash_code_start":134443008,"­flash_length":262144}
    {"free":778,"usage":1022,"total":1800,"h­istory":18,"stackEndAddress":536909512,"­flash_start":134217728,"flash_binary_end­":134432224,"flash_code_start":134443008­,"flash_length":262144}
    

    Each test if the variable exists creates the variable as undefined and uses memory.
    You will see it when you output the array like this:

    console.log(test);
    

    Output:

    {"hello0":undefined,"hello1":undefined,"­hello2":undefined,"hello3"...........
    

    Many thanks for your help

    Sacha

  • This is nasty!

    Does 'delete varname' clean up after it?

  • Hi DrAzzy,

    Yes as any other variable it could be deleted. It gives the mem back.

    Sacha

  • I believe it's this one https://github.com/espruino/Espruino/iss­ues/63

    Just an idea I didn't test, but how about

    if (Object.keys(test).indexOf("bar") !== -1) {...}
    

    Would that make sense?

  • Yes, it looks like. Thanks. Will try it.

    Sacha

  • Or you can do if ("bar" in test) ... which is a bit faster/easier.

    At the moment this is a frustrating issue - but it's surprising how rarely it's actually a problem if your code is working as expected.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Check if a variable exists - Memory ?

Posted by Avatar for Sacha @Sacha

Actions