且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字符串+ = s1和字符串=字符串+ s1之间的区别

更新时间:2022-03-17 04:37:09

对于内置类型a += ba = a + b完全相同(除了a仅被评估一次) ),但对于类,这些运算符会重载并调用不同的函数.
在您的示例中,fans = fans + s[i]创建一个临时字符串,并将其分配(移动)到fans,但是fans += s[i]不会创建该临时字符串,因此可能会更快.

For built-in types a += b is exactly the same as a = a + b (except that a is evaluated only once), but for classes, those operators are overloaded and call different functions.
In your example fans = fans + s[i] creates a temporary string, and assigns (moves) it to fans, but fans += s[i] does not create that temporary, hence it may be faster.