1. Checking empty string
In old days (version 1.5 and lower) we used String.equal(""), but 1.6 brought us String.IsEmpty which is better and faster.
// wrong/slow
if (name.equals("")) {
// correct/fast
if (name.isEmpty()) {
2. Concatenation
Method String.concat creates new String object, it's OK to use it when you do operation only once, otherwise use operator + += operators (see below why).
String s = "Hello ".concat("new").concat(" world!"); // "Hello new world!"
Using operators + and +=, they do not use String.concat method but StringBuilder and it's important to know what it means to us. String s = "Hello " + "new" + " world!"; // "Hello new world!"
What actually happens when you use + operator is StringBuilder used: String s = new StringBuilder().append("Hello ").append("new").append(" world!").toString(); // "Hello new world!"
So conclusion - it's ok to use concat if you do one time operation, for any other situation I would recommend to use + or +=.3. String Formatting
Very often in order to format string people either concatenate the string to achieve result or do replace or invent something else. I do it as well sometimes (what a shame!). Instead we should use String.format method to do that.
int n = 10;
// wrong
String s = "I have " + Integer.toString(10) + " books";
// wrong
String s = "I have #num books".replace("#num", Integer.toString(10));
// correct
Strig s = String.format("I have %d books", n);
I would be glad to hear other typical mistakes we do with String object! So please share your experience.
2 comments :
Regarding the StringBuilder thing... I wasn't sure about this so I checked with Devin Olson. He said :
===
ok, for single line concatenation,
String s = “abc” + “def” + “ghi”,
the compiler will turn this into:
String s = new StringBuilder().append(“abc”).append(“def”).append(“ghi).toString()
which is fine,but if you are concatenating in a loop with “+” symbols, the compiler will generate a NEW StringBuilder object during each iteration, which is the exact opposite of optimized code.
=====
So I THINK the moral of the story is if you're building a string from a loop you really want to make your own Stringbuilder object at least....
Just a thought. thanks for the post!!
@David Leedy, thank for update and moral you mentioned is perfectly correct :)
Post a Comment