java - 为什么用String替换StringBuilder
黄舟
黄舟 2017-04-18 10:25:48
0
4
664

今天在用android studio 2.0的时候碰到个奇怪问题:
我用StringBuilder生成一个字符串,但是用studio自带的代码检测程序优化代码时,缺把StringBuilder改成了String型“+”连接。
这是什么原因呢?不是StringBuilder应该比“+”性能更好吗?
这是自动替换后的

String sb = "CREATE TABLE IF NOT EXISTS " +
                appContext.getString(R.string.tbl_name) +
                "(_id INTEGER PRIMARY KEY AUTOINCREMENT" +
                ",account VARCHAR" +
                ",psw VARCHAR" +
                ",memo TEXT)";

这是我之前写的

StringBuilder sb = new Stringbuilder();
sb.append(xxxx)
.
.
.
db.execSql(sb.toString());
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(4)
PHPzhong

The splicing compiler that is all constants will optimize it for you. You can check the bytecode of the compiled class file after the replacement. It should be better than what you wrote

Think about it, what scort said should make sense. The compiler should optimize the + connection of string constants during the compilation phase, so there is no need for StringBuilder

阿神

The compiler optimizes the connector internally. If it is a constant, it is directly spliced ​​through the constant pool

If it is non-constant, in most cases it will be optimized internally like this, new StringBuilder().append(), and finally toString() will be called, at least this is the case on jdk1.7

刘奇

The content of the StringBuilder object can be modified, which is better than the String class in terms of memory usage.
The String object cannot be modified once it is generated. Reassignment is actually two objects.

So in actual use, if you often need to modify a string, such as insertion, deletion, etc., it is more suitable to use StringBuilder.

In addition, the editor's checker is just a specification, not necessarily the best.

Peter_Zhu

This is the optimization of the compiler. If you have multiple lines, that is, multiple ";" as connections, it will not be optimized

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!