=和<<之间的Ruby差异以连接字符串
发布时间:2020-12-16 23:23:57 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why is the shovel operator () preferred over plus-equals (+=) when building a string in Ruby?7个 在Ruby 1.8.7上,当发现和=在String对象上: y = "" start = Time.now 99999.times { |x| y += "some new string" } puts "Time: #{Time.no
参见英文答案 >
Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby?7个
在Ruby 1.8.7上,当发现<<<<<<<<<<<<<<<<<<和=在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 我谷歌了解一下,发现了一些结果: http://www.rubylove.info/post/1038516765/difference-between-string-concatenation-ruby-rails 说<<<修改两个字符串,而=仅修改调用者.我不明白为什么然后<<快点. 接下来我去了Ruby doc,但我想知道为什么没有方法= http://ruby-doc.org/core-2.2.0/String.html 解决方法
挖掘机运算符<<因为铲子操作符允许修改原始字符串,所以在处理长字符串时执行要好得多,而每次运行时,=必须将第一个字符串中的所有文本复制到新字符串中. String类上没有定义=运算符,因为=是组合运算符.简而言之,x =“asdf”完全等同于x = x“asdf”,因此您应该在字符串类上引用运算符,而不是查找a =运算符.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |