安卓的StringBuilder VS字符串连接字符串、StringBuilder、VS

2023-09-04 13:07:00 作者:独角兽妹妹

我在读这个文档页面,http://developer.android.com/reference/android/util/Log.html.

I was reading this documentation page, http://developer.android.com/reference/android/util/Log.html.

本节在这里引起了我的注意:

The section here caught my eye:

提示:不要忘记,当你做出这样

Tip: Don't forget that when you make a call like

Log.v(TAG,指数=+ I);

,当你正在构建的字符串传递到Log.d,编译器   使用一个StringBuilder和至少三个分配发生:所述   StringBuilder的本身,缓冲器,以及字符串对象。   实际上,还有另外一个缓冲区分配及副本,   更pressure的GC。这意味着,如果你的日志信息是   过滤掉,你可能会做显著的工作和承担   显著的开销。

that when you're building the string to pass into Log.d, the compiler uses a StringBuilder and at least three allocations occur: the StringBuilder itself, the buffer, and the String object. Realistically, there is also another buffer allocation and copy, and even more pressure on the gc. That means that if your log message is filtered out, you might be doing significant work and incurring significant overhead.

这意味着Android的编译器正在字符串连接(+),并将其转换成的StringBuilder和附加声明。

This implies that the Android compiler is taking string concatenations (+) and converting them into StringBuilder and append statements.

是我的假设是正确的还是仍然最好使用字符串连接StringBuilder的手工呢?

推荐答案

编译器不正是你的建议是隐含的。您可以打印生成的.class文件的字节codeS(使用的javap -c ),看看构造和使用 StringBuilder的调用

The compiler does exactly what you suggest is implied. You can print the bytecodes of the generated .class file (using javap -c) and see the calls to construct and use a StringBuilder.

然而,它通常值得做手工时字符串连接有s $ P $垫了几行code。编译器通常会分配一个单独的的StringBuilder 为每个字符串值EX pression涉及 +

However, it's generally worth doing it manually when the string concatenations are spread over several lines of code. The compiler usually allocates a separate StringBuilder for every String-valued expression involving +.