Java:toString vs. string concatentation?

时间:2015-10-29 02:43:24

标签: java string

在将对象转换为字符串表示时,是否有理由更喜欢字符串连接或调用toString

字符串连接是否会导致调用对象的String s; Properties p = System.getProperties(); s = p.toString(); s = "" + p; 方法?

    var activeGamesCurrentUser = 0

    gamesQuery.countObjectsInBackgroundWithBlock({
            (count, error) -> Void in
            let countedInt = Int(UInt32(count))
            self.activeGamesCurrentUser = countedInt
        })

1 个答案:

答案 0 :(得分:2)

p.toString()更好。

当你说s ="" + p时,编译器会这样:

{
    StringBuilder sb = new StringBuilder();
    sb.append("").append(p.toString());
    s=sb.toString();
}

所以,是的,"" + p确实意味着调用了p.toString(),但它也增加了许多额外的工作。

可能发生的最好的事情是编译器认识到它与p.toString()相同,而只是调用它,但你不应该依赖它。