gpt4 book ai didi

java - 将整数连接到字符串 - 从性能和内存的角度来看,使用字符串文字还是原语?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:06:17 25 4
gpt4 key购买 nike

选项 1:

String newStr = someStr + 3 + "]";

选项 2:

String newStr = someStr + "3" + "]";

哪个选项在性能、内存和一般实践方面更好?我可以使用哪些推荐的工具/方法来测量我的代码的内存使用情况及其性能(除了测量开始时间和结束时间并计算差异之外)

最佳答案

第一个会变成:

StringBuilder sb = new StringBuilder (String.valueOf (someStr));
sb.append (3);
sb.append ("]");
String newStr = sb.toString ();

第二个会变成:

StringBuilder sb = new StringBuilder (String.valueOf (someStr));
sb.append ("3");
sb.append ("]");
String newStr = sb.toString ();

这里是反汇编:

public String foo (String someStr)
{
String newStr = someStr + 3 + "]";
return newStr;
}

public String bar (String someStr)
{
String newStr = someStr + "3" + "]";
return 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 - 将整数连接到字符串 - 从性能和内存的角度来看,使用字符串文字还是原语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14782804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com