今天在用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());
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.
This is the optimization of the compiler. If you have multiple lines, that is, multiple ";" as connections, it will not be optimized