{
StringBuilder fileBuff = new StringBuilder();
long before = getUsedMem();
try {
//Open InputStreamReader here
while ((currLine = lnr.readLine()) != null) {
fileBuff.append("\r\n" + currLine);
}
//Close streams
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("usedTotal: " + (getUsedMem() - before));
}
private long getUsedMem() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
While running the code several times, I get usedTotal ~ 14279888, but if I replace with fileBuff.append("\r\n").append(currLine)
I get almost double the memory ~33264440.
Can somebody please explain the reason, as I know String
concatenation also uses StringBuilder
?
I: fileBuff.append("\r\n" + currLine);
62: aload 6
64: invokevirtual #16 // Method java/io/LineNumberReader.readLine:()Ljava/lang/String;
67: dup
68: astore_2
69: ifnull 99
72: aload_1
73: new #2 // class java/lang/StringBuilder
76: dup
77: invokespecial #3 // Method java/lang/StringBuilder."<init>":()V
80: ldc #17 // String \r\n
82: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
85: aload_2
86: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
89: invokevirtual #10 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
92: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
95: pop
96: goto 62
II fileBuff.append("\r\n").append(currLine)
62: aload 6
64: invokevirtual #16 // Method java/io/LineNumberReader.readLine:()Ljava/lang/String;
67: dup
68: astore_2
69: ifnull 86
72: aload_1
73: ldc #17 // String \r\n
75: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
78: aload_2
79: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
82: pop
83: goto 62
Clearly #II should use less memory, but it doesn't. The file I am reading is 50k long.