+ =和

时间:2021-08-17 23:30:19

This question already has an answer here:

这个问题在这里已有答案:

On Ruby 1.8.7 I was doing a loop concatenating strings when found out that there seems to be a HUGE difference between << and += on a String object:

在Ruby 1.8.7上,当发现在String对象上< <和+ =之间似乎存在巨大差异时,我正在进行循环连接字符串:< p>

 y = ""
 start = Time.now
 99999.times { |x| y += "some new string"  }
 puts "Time: #{Time.now - start}"
 # Time: 31.56718

 y=''
 start = Time.now
 99999.times { |x| y << "some new string"  }
 puts "Time: #{Time.now - start}"
 # Time: 0.018256

I google about that, found some results:

我谷歌了解一下,发现了一些结果:

http://www.rubylove.info/post/1038516765/difference-between-string-concatenation-ruby-rails

Says that << modifies both strings, while += only modify the caller. I don't understand why is then << faster.

说< <修改两个字符串,而+ =只修改调用者。我不明白为什么然后“更快。< p>

Next I went to the Ruby doc, but I wonder WHY there is no method +=

接下来我去了Ruby doc,但我想知道为什么没有方法+ =

http://ruby-doc.org/core-2.2.0/String.html

1 个解决方案

#1


10  

The shovel operator << performs much better than += when dealing with long strings because the shovel operator is allowed to modify the original string, whereas += has to copy all the text from the first string into a new string every time it runs.

铲斗操作符< <在处理长字符串时执行比+ =好得多,因为允许铲操作符修改原始字符串,而+="必须在每次运行时将第一个字符串中的所有文本复制到新字符串中。

There is no += operator defined on the String class, because += is a combined operator. In short x += "asdf" is exactly equivalent to x = x + "asdf", so you should reference the + operator on the string class, not look for a += operator.

String类上没有定义+ =运算符,因为+ =是组合运算符。简而言之,x + =“asdf”完全等同于x = x +“asdf”,因此您应该在字符串类上引用+运算符,而不是查找+ =运算符。

#1


10  

The shovel operator << performs much better than += when dealing with long strings because the shovel operator is allowed to modify the original string, whereas += has to copy all the text from the first string into a new string every time it runs.

铲斗操作符< <在处理长字符串时执行比+ =好得多,因为允许铲操作符修改原始字符串,而+="必须在每次运行时将第一个字符串中的所有文本复制到新字符串中。

There is no += operator defined on the String class, because += is a combined operator. In short x += "asdf" is exactly equivalent to x = x + "asdf", so you should reference the + operator on the string class, not look for a += operator.

String类上没有定义+ =运算符,因为+ =是组合运算符。简而言之,x + =“asdf”完全等同于x = x +“asdf”,因此您应该在字符串类上引用+运算符,而不是查找+ =运算符。