【问题标题】:Ruby differences between += and << to concatenate a string [duplicate]+= 和 << 连接字符串的 Ruby 区别 [重复]
【发布时间】:2015-07-11 12:36:06
【问题描述】:

在 Ruby 1.8.7 上,当我发现 &lt;&lt;+=String 对象上似乎存在巨大差异时,我正在执行一个连接字符串的循环:

 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

我google了一下,找到了一些结果:

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

表示&lt;&lt; 修改了两个字符串,而+= 只修改了调用者。我不明白为什么然后&lt;&lt; 更快。

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

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

【问题讨论】:

  • Related: stackoverflow.com/questions/4684446/… (实际上,这甚至可能是重复的?)
  • 您链接到的文章说&lt;&lt; 修改了两个字符串是不正确的。 originalcopy 变量引用同一个字符串对象。
  • @Adrian 正确。那篇文章的作者似乎误解了该代码发生了什么。事实上,“副本”根本不是真正的副本,只是对同一个 String 对象的引用。

标签: ruby string


【解决方案1】:

铲子运算符&lt;&lt; 在处理长字符串时比+= 执行得更好,因为铲子运算符允许修改原始字符串,而+= 必须将第一个字符串中的所有文本复制到一个新字符串中每次运行时字符串。

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

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 2018-11-10
    • 2017-08-08
    • 1970-01-01
    • 2019-01-12
    • 2012-10-10
    • 2014-06-12
    • 1970-01-01
    相关资源
    最近更新 更多