java - Memory efficient way to initialize a String to be reused inside a loop -


i'm using couple of strings in code going reused within loop , i'm wondering best way initialize string variables improve memory usage:

// sample purposes declare map, same thing // applies arraylist, database set, etc. point. map<string, string> samplemap = getmap(); int mapsize = samplemap.size();  // string initialization string a; string b = new string(); string c = "";  for(int = 0; < mapsize; i++){     = samplemap.get(i);     b = somefunc(a);     c = anotherfunc(a);     // stuff strings } 

after loop, strings no longer used.

you cannot optimize initialization or memory usage of strings in snippet of code, several reasons:

  1. java strings immutable - cannot change characters inside string, can point new string.

  2. in loop, called function (such afunc() or get()) 1 responsible allocating string, not loop.

for advanced programmers: if want optimize memory usage of strings, need use stringbuffer/stringbuilder or raw character array , pass them around various function calls. you'd create buffer before loop, , pass get() , other functions, use 1 buffer instead of allocating , returning own.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -