Shop OBEX P1 Docs P2 Docs Learn Events
Memory Usage & Dec to Hex — Parallax Forums

Memory Usage & Dec to Hex

trytryagaintrytryagain Posts: 26
edited 2009-09-23 19:06 in General Discussion
To anyone interested:

Peter - thank you for your dec to hex help,
·········· your last example worked great.

Now that my interest has peaked in a dec to hex converter,
below is some code that I think could replace your example
without utilizing the (import stamp.util.text.*) method bprintf··

PETER'S:

static char[noparse]/noparse cBuffer = new char[noparse][[/noparse]60];·····

while (fingerReceive.byteAvailable() == true) {·
int b = fingerReceive.receiveByte();
cIndex = Format.bprintf(cBuffer,cIndex,"%02x",b&0xFF);
}


MINE:

The method below returns the same results as above
except this routine slowly uses more memory(VERY BAD)
I've detected with a periodic call to: System.out.println(Memory.freeMemory());

Can anyone tell me why the sub Dec2Hex EATS MEMORY?
All variables are declared static outside the function.
ANY FIX TO MY MEMORY EATER WOULD BE APPRECIATED


NEW:

while (fingerReceive.byteAvailable() == true) {·
buffer.append(Dec2Hex(b&0xFF));
}


static String hex;
static int digit;
static int length;
static String [noparse]/noparse HexCodes = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};·················

· public static String Dec2Hex(int d) {
······· if (d == 0) return "00";
······· hex = "";
······· while (d > 0) {
··········· digit = d % 16;
··········· hex = HexCodes[noparse][[/noparse]digit] + hex;
··········· d = d / 16;
······· }
······· length = hex.length();
······· if (length < 2)
······· {
······· return "0" + hex;
······· }
······· else
······· {
······· return hex;
······· }
··· }

Thanks,

Jeff (trytryagain)
·

Comments

  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2009-09-23 17:30
    The problem of memory leak is caused by
    "0" + hex
    The javelin creates a temporary string each time and since there
    is no garbage collection these temporary strings are not returned
    to the heap.

    while (fingerReceive.byteAvailable() == true) {  
    buffer.append(Dec2Hex(b));
    }
     
     
    static StringBuffer stemp = new StringBuffer();
    

    public static String Dec2Hex(int d) {
      stemp.clear();
      int digit = '0' + ((d>>4)&0x0F);
      if (digit > '9') digit += 7;
      stemp.append(char)digit);  
      digit = '0' + (d&0x0F);
      if (digit > '9') digit += 7;
      stemp.append(char)digit);  
      return stemp.toString();
    }
    

    regards peter
  • trytryagaintrytryagain Posts: 26
    edited 2009-09-23 19:06
    Thank you again

    I dub you Peter The Great!

    My lesson here is stay away from concat with +

    This also taught me to monitor memory at all

    times. Progams won't loop for long with leaks.

    Thanks again my friend

    Jeff (trytryagain)
Sign In or Register to comment.