Memory optimization in the code

Posted on
  • Hi,
    I have wrote a software which uses a lot of object instantiated only at the boot.
    I need to save memory and delete unused data.

    for example, this code allow me to instantiate more objects each assigned to a multicolor LED:

    TRILED=function(pin1,pin2){
      this.id1=pin1;
      this.id2=pin2;
    };
    TRILED.prototype.reset=function(){
      this.id1.reset();
      this.id2.reset();
    };
    TRILED.prototype.setRED=function(){
      this.id1.set();
      this.id2.reset();
    };
    
    TRILED.prototype.setGREEN=function(){
      this.id1.reset();
      this.id2.set();
    };
    TRILED.prototype.setYELLOW=function(){
      this.id1.set();
      this.id2.set();
    };
    
    L1=new TRILED(A0,A1)
    L2=new TRILED(A2,A3)
    L3=new TRILED(A4,A5)
    

    The question is: Can I safely delete the TRILED object after their initialization? Can safely call the method set* and reset in the future ?

    It seems to works but I need a confirmation, I want to do this:

    L1=new TRILED(A0,A1)
    L2=new TRILED(A2,A3)
    L3=new TRILED(A4,A5)
    
    delete TRILED;
    
    L1.setRED();
    L2.setGREEN();
    ....etc...etc
    
  • Yes, you can do that - but it won't save you a great deal of memory (only a few variables)...

    While the TRILED object reference will be deleted, the object itself will still hang around because it's used by L1,L2,etc.

    You can check how much memory you are using before and after the delete using process.memory().usage

  • Since you - @Francesco - use objects that creates a namespace for methods, you can chose shorter method names, such as sR(), sG(), ...and sC(r,g,b) - for setting a particular or continues color and that will save you probably more space than deleting the constructor (source)... assumed your overall code will not be shrink wrapped (bulked and minified).

  • thanks both for the reply, I have solved in other way that I'll explain:

    For my partcular case the core of the software is a function called at regular intervals, and I choose at boot time what function run (I have defined N function, one for each "mode").
    Considering that other N-1 functions will be never called I can safely delete it with

    delete MyOBJ.prototytpe.myfuncion
    

    before the chosen function is called

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

Memory optimization in the code

Posted by Avatar for Francesco @Francesco

Actions