简体   繁体   English

通过'+'运算符Concat进行字符串连接

[英]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(hourString);
}

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? 如果我在程序中有很多字符串连接并且我在'concat'方法上使用'+'运算符,反之亦然,会有性能问题吗?

Either way you'll be creating a lot of unnecessary temporary String s. 无论哪种方式,您都将创建很多不必要的临时String Strongly recommend using StringBuilder instead. 强烈建议改用StringBuilder 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. 当您使用+运算符时,编译器实际上将使用临时StringBuilder实例,但是它对您要实现的目标没有更广阔的视野,并且在优化StringBuilder使用量方面受到限制,因此您几乎总是做得更好,使之明确。

I think both are more or less equivalent. 我认为两者大致相同。 However, if your concerned about performance, you should use StringBuilder for string concatenation. 但是,如果您担心性能,则应使用StringBuilder进行字符串连接。

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM