我正在阅读此文档页面,http://developer.android.com/reference/android/util/Log.html .
这里的部分引起了我的注意:
Tip: Don't forget that when you make a call like
Log.v(TAG, "index=" + i);
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 和追加语句。
我的假设是否正确,还是手动使用 StringBuilder 而不是字符串连接更好?
最佳答案
编译器完全按照您的建议进行操作。您可以打印生成的 .class 文件的字节码(使用 javap -c
)并查看构造和使用 StringBuilder
的调用。
但是,当字符串连接分布在多行代码中时,手动执行此操作通常是值得的。编译器通常为每个涉及 +
的字符串值表达式分配一个单独的 StringBuilder
。
关于Android StringBuilder 与字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8553824/