gpt4 book ai didi

java - 为什么 String 连接比 Java 中的 StringBuilder 快?

转载 作者:行者123 更新时间:2023-11-29 08:35:41 27 4
gpt4 key购买 nike

此程序将对象的状态转换为 HTML 字符串。

public class Test {
public static void main(String[] args) {
Address addr = new Address();
addr.setLine1("A straight line");
addr.setLine2("A curve");
addr.setCity("A Round City");
addr.setState("A Triangular State");
addr.setCountry("A Rectangle Country");
addr.setZip("123456");

@SuppressWarnings("unused")
String str;
int count = 1000;
for (int j = 0; j < 5; j++) {

double timeRich = System.nanoTime();
for (int i = 0; i < count; i++) {
str = AddressFormatter.formatRich(addr);
}
timeRich = System.nanoTime() - timeRich;

double timeFine = System.nanoTime();
for (int i = 0; i < count; i++) {
str = AddressFormatter.formatFine(addr);
}
timeFine = System.nanoTime() - timeFine;


double timePoor = System.nanoTime();
for (int i = 0; i < count; i++) {
str = AddressFormatter.formatPoor(addr);
}
timePoor = System.nanoTime() - timePoor;

System.out.println("Test cases: " + count);
System.out.println("Average time to format (SB Poor): " + (int)(timePoor/count) + " ns");
System.out.println("Average time to format (SB Fine): " + (int)(timeFine/count) + " ns");
System.out.println("Average time to format (String) : " + (int)(timeRich/count) + " ns");
System.out.println();
count *= 10;
}
System.out.println("***End of test***");
}
}

class Address {
private String line1;
private String line2;
private String city;
private String state;
private String country;
private String zip;

/**
* Default constructor.
*/
public Address() {}

public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}

class AddressFormatter {
// more readable than formatFine()
public static String formatPoor(Address obj) {
StringBuilder str = new StringBuilder();
str.append("<div class=\"address-wrapper\">\n");
str.append("\t<div class=\"addr-line\">" + obj.getLine1() + "</div>\n");
str.append("\t<div class=\"addr-line\">" + obj.getLine2() + "</div>\n");
str.append("\t<div class=\"addr-city\">" + obj.getCity() + "</div>\n");
str.append("\t<div class=\"addr-state\">" + obj.getState() + "</div>\n");
str.append("\t<div class=\"addr-country\">" + obj.getCountry() + "</div>\n");
str.append("\t<div class=\"addr-zip\">" + obj.getZip() + "</div>\n");
str.append("</div>\n");

return str.toString();
}

// grouping all constants, removing string concatenations
public static String formatFine(Address obj) {
StringBuilder str = new StringBuilder();
str.append("<div class=\"address-wrapper\">\n\t<div class=\"addr-line\">");
str.append(obj.getLine1());
str.append("</div>\n\t<div class=\"addr-line\">");
str.append(obj.getLine2());
str.append("</div>\n\t<div class=\"addr-city\">");
str.append(obj.getCity());
str.append("</div>\n\t<div class=\"addr-state\">");
str.append(obj.getState());
str.append("</div>\n\t<div class=\"addr-country\">");
str.append(obj.getCountry());
str.append("</div>\n\t<div class=\"addr-zip\">");
str.append(obj.getZip());
str.append("</div>\n</div>\n");

return str.toString();
}

public static String formatRich(Address obj) {
return "<div class=\"address-wrapper\">\n"
+ "\t<div class=\"addr-line\">" + obj.getLine1() + "</div>\n"
+ "\t<div class=\"addr-line\">" + obj.getLine2() + "</div>\n"
+ "\t<div class=\"addr-city\">" + obj.getCity() + "</div>\n"
+ "\t<div class=\"addr-state\">" + obj.getState() + "</div>\n"
+ "\t<div class=\"addr-country\">" + obj.getCountry() + "</div>\n"
+ "\t<div class=\"addr-zip\">" + obj.getZip() + "</div>\n"
+ "</div>\n";
}
}

在 Eclipse 中运行这个程序时得到以下结果:

Test cases: 1000
Average time to format (SB Poor): 13513 ns
Average time to format (SB Fine): 7052 ns
Average time to format (String) : 14088 ns

Test cases: 10000
Average time to format (SB Poor): 3061 ns
Average time to format (SB Fine): 3290 ns
Average time to format (String) : 1618 ns

Test cases: 100000
Average time to format (SB Poor): 3486 ns
Average time to format (SB Fine): 1568 ns
Average time to format (String) : 589 ns

Test cases: 1000000
Average time to format (SB Poor): 616 ns
Average time to format (SB Fine): 547 ns
Average time to format (String) : 497 ns

Test cases: 10000000
Average time to format (SB Poor): 657 ns
Average time to format (SB Fine): 626 ns
Average time to format (String) : 191 ns

***End of test***

为什么 String 版本比 StringBuilder 版本快?

为什么每次迭代后平均时间都在减少?

编辑:我通过从“StringBuilder”版本中删除所有连接操作来添加另一个格式化函数(正如一个答案所指出的)。

在第一次迭代中,“String”版本是最慢的。

在最后一次迭代中,'String' 版本是最快的。

最佳答案

问题的第二部分很简单:JVM 正在识别重复执行并优化机器代码,这就是为什么 it's important to handle benchmarks carefully .

以下是解释实现差异的原因:

您的“StringBuilder”实现写得非常糟糕。您不是附加每个组件,而是执行字符串连接(创建然后丢弃新的 StringBuilder)为每个方法调用,然后附加其结果。如果您正确地为每个元素使用 .append,您会发现差异会小得多。

但是,现代 Java 编译器将一系列使用 + 的字符串连接转换为隐式 StringBuilder 调用,以最大限度地减少对象创建。 Java 编译器还会合并连接在一起的编译时字符串常量。因此,您的 format2 方法使用了 StringBuilder,但有一个重要区别——所有换行的相邻字符串常量都被合并。因此,即使您要修复 format 方法,format2 也会更快,因为它对更多固定内容进行了分组。

关于java - 为什么 String 连接比 Java 中的 StringBuilder 快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44239633/

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