java - Initializing Strings using New or not? -


this question has answer here:

i wanted know if same this, in terms of optimization , performance:

public class test {      public static void main(string[] args) {                  string option1 = "text 1";         string option2 = "text 2";         string option3 = "text 3";  } 

than following:

public class test {      public static void main(string[] args) {                  string option1 = new string("text 1");         string option2 = new string("text 2");         string option3 = new string("text 3");  } 

the second option make copy of original string. not want, if on memory-constrained platform or if perform operation large number of times, cause lot of garbage collection and, ultimately, outofmemoryerror.

as example, have created following example.

public class outie {      public static void main(string[] args) {         java.util.arraylist<string> al = new java.util.arraylist<string>();         while (true) {             al.add(new string("outie"));         }     } } 

when compiled , run, incremental , full gc run several times before program abends.

$ java -verbosegc outie [gc 27648k->21021k(106048k), 0.0232500 secs] [gc 48669k->39738k(133696k), 0.0251830 secs] [gc 82898k->82549k(138880k), 0.0513920 secs] [full gc 82549k->75130k(226880k), 0.6177140 secs] [gc 124479k->139363k(252672k), 0.0547170 secs] [full gc 139363k->112517k(352448k), 0.6634360 secs] [gc 185168k->208879k(381952k), 0.0711140 secs] [full gc 208879k->168535k(515520k), 1.1115060 secs] [gc 277163k->312989k(571200k), 0.1107330 secs] [gc 379933k->307985k(615616k), 0.1115700 secs] [gc 374929k->374905k(618944k), 0.1452780 secs] [gc 521181k->467291k(650752k), 0.7257080 secs] [gc 532443k->532619k(687936k), 1.1450690 secs] [full gc 532619k->507837k(965824k), 3.0001520 secs] [gc 720339k->720812k(965824k), 0.8367880 secs] [gc 811628k->811932k(998976k), 0.8454970 secs] [full gc 811932k->730029k(1352448k), 3.9708660 secs] [gc 1036526k->1037014k(1352448k), 0.8832300 secs] [gc 1160982k->1161502k(1400576k), 0.8352880 secs] [full gc 1161502k->1038805k(1544192k), 5.5201590 secs] [gc 1205141k->1205495k(1544192k), 0.9881680 secs] [gc-- 1281377k->1423593k(1544192k), 1.6090210 secs] [full gc 1423593k->1277979k(1544192k), 7.9840780 secs] [full gc 1277979k->1277965k(1544192k), 6.1397000 secs] exception in thread "main" java.lang.outofmemoryerror: java heap space     @ java.util.arrays.copyof(arrays.java:2245)     @ java.util.arrays.copyof(arrays.java:2219)     @ java.util.arraylist.grow(arraylist.java:213)     @ java.util.arraylist.ensurecapacityinternal(arraylist.java:187)     @ java.util.arraylist.add(arraylist.java:411)     @ outie.main(outie.java:6) 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -