Java编译器不会自动优化String串联吗? [英] Java compiler doesn't optimize String concatenation automatically?

查看:139
本文介绍了Java编译器不会自动优化String串联吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 Jsoup 代码将容器els中所有元素的文本:

The following Jsoup code concatenates the text of all elements in container els:

for (Element el : els)
  entireText += el.text();          

在具有〜64个元素的容器中,每个元素包含〜1KB(totalText总计为〜64KB),在典型的低端Android手机上,此简单循环大约需要 8秒.

On a container with ~64 elements, each containing ~1KB (totaling in entireText being ~64KB), this simple loop takes about 8 seconds on a typical low-end Android phone.

这种缓慢的性能使我感到惊讶,因为我印象中Java编译器将A + B + C之类的表达式替换为new StringBuilder(A).append(B).append(C).toString().

This slow performance kind of surprises me because I was under the impression that Java compilers substitute expressions like A + B + C with new StringBuilder(A).append(B).append(C).toString().

不是这样吗?

我想念什么?

推荐答案

这种缓慢的表现让我感到惊讶,因为我当时处于 Java编译器替代A + B + C之类的表达式的印象 带有新的StringBuilder(A).append(B).append(C).toString().

This slow performance kind of surprises me because I was under the impression that Java compilers substitute expressions like A + B + C with new StringBuilder(A).append(B).append(C).toString().

因此,编译器将创建代码:

And so the compiler creates the code:

for (Element el : els)
  entireText = new StringBuilder(entireText).append(el.text()).toString(); 

您将需要在循环外部创建StringBuilder并手动将其追加.

You will need to create the StringBuilder outside the loop and append to it manually.

这篇关于Java编译器不会自动优化String串联吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆