Wednesday, 15 January 2014

java - Concat an integer to a String - use String literal or primitive from performance and memory point of view? -



java - Concat an integer to a String - use String literal or primitive from performance and memory point of view? -

option 1:

string newstr = somestr + 3 + "]";

option 2:

string newstr = somestr + "3" + "]";

which alternative improve regards performance, memory , general practice? recommended tools/ways can utilize measure memory usage of code , performance (besides measuring start time , end time , calculate difference)

the first become:

stringbuilder sb = new stringbuilder (string.valueof (somestr)); sb.append (3); sb.append ("]"); string newstr = sb.tostring ();

the sec become:

stringbuilder sb = new stringbuilder (string.valueof (somestr)); sb.append ("3"); sb.append ("]"); string newstr = sb.tostring ();

here disassembly:

public string foo (string somestr) { string newstr = somestr + 3 + "]"; homecoming newstr; } public string bar (string somestr) { string newstr = somestr + "3" + "]"; homecoming newstr; } public java.lang.string foo(java.lang.string); code: 0: new #16 // class java/lang/stringbuilder 3: dup 4: aload_1 5: invokestatic #18 // method java/lang/string.valueof:(ljava/lang/object;)ljava/lang/string; 8: invokespecial #24 // method java/lang/stringbuilder."<init>":(ljava/lang/string;)v 11: iconst_3 12: invokevirtual #27 // method java/lang/stringbuilder.append:(i)ljava/lang/stringbuilder; 15: ldc #31 // string ] 17: invokevirtual #33 // method java/lang/stringbuilder.append:(ljava/lang/string;)ljava/lang/stringbuilder; 20: invokevirtual #36 // method java/lang/stringbuilder.tostring:()ljava/lang/string; 23: astore_2 24: aload_2 25: areturn public java.lang.string bar(java.lang.string); code: 0: new #16 // class java/lang/stringbuilder 3: dup 4: aload_1 5: invokestatic #18 // method java/lang/string.valueof:(ljava/lang/object;)ljava/lang/string; 8: invokespecial #24 // method java/lang/stringbuilder."<init>":(ljava/lang/string;)v 11: ldc #44 // string 3 13: invokevirtual #33 // method java/lang/stringbuilder.append:(ljava/lang/string;)ljava/lang/stringbuilder; 16: ldc #31 // string ] 18: invokevirtual #33 // method java/lang/stringbuilder.append:(ljava/lang/string;)ljava/lang/stringbuilder; 21: invokevirtual #36 // method java/lang/stringbuilder.tostring:()ljava/lang/string; 24: astore_2 25: aload_2 26: areturn

java string concatenation primitive

No comments:

Post a Comment