开发者

Concat over '+' operator for string concatenation

String today = someSimpleDateFormat.format(new Date());
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
int minute = rightNow.get(Calendar.MINUTE);
String hourString = String.valueOf(hour);
String minuteString = String.valueOf(minute);

if(hourString.length() == 1){
    hourString = '0'.concat(hour开发者_开发技巧String);
}

if(minuteString.length() == 1){
    minuteString = '0'.concat(minuteString);
}

String dayHourMinute = today.concat("_").concat(hourString).concat("_").concat(minuteString);       

I could have used '+' operator. Would there be any performance issue if I have lots of string concatenation in the program and I use '+' operator over the 'concat' method or viceversa?


Either way you'll be creating a lot of unnecessary temporary Strings. Strongly recommend using StringBuilder instead. The compiler will actually use temporary StringBuilder instances when you use the + operator, but it doesn't have the broader vision of what you're trying to achieve and is limited in terms of how much it can optimize the StringBuilder use, so you'll almost always do a better job making it explicit.


I think both are more or less equivalent. However, if your concerned about performance, you should use StringBuilder for string concatenation.


It doesn't really matter:

Yes, you should avoid the obvious beginner mistakes of string concatenation, the stuff every programmer learns their first year on the job. But after that, you should be more worried about the maintainability and readability of your code than its performance. And that is perhaps the most tragic thing about letting yourself get sucked into micro-optimization theater -- it distracts you from your real goal: writing better code.


If you don't have performance issues, consider the following alternative, which I find easier to read:

String dayHourMinute = 
     String.format("%s_%s_%s", today, hourString, minuteString);
String evenBetter = 
     String.format("%s_%02d_%02d", today, hourString, minuteString);
// thanks to hardcoded!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜