Ruby - Array.join 与字符串连接(效率) [英] Ruby - Array.join versus String Concatenation (Efficiency)

查看:69
本文介绍了Ruby - Array.join 与字符串连接(效率)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得曾几何时因为在 Python 中连接字符串而受到责骂.有人告诉我,在 Python 中创建一个字符串列表并稍后加入它们会更有效.我将这种做法带到了 JavaScript 和 Ruby 中,尽管我不确定这在后者中是否有同样的好处.

I recall getting a scolding for concatenating Strings in Python once upon a time. I was told that it is more efficient to create an List of Strings in Python and join them later. I carried this practice over into JavaScript and Ruby although I am unsure if this has the same benefit in latter.

谁能告诉我加入字符串数组并在它们上调用 :join 或根据需要在 Ruby 编程语言中连接字符串是否更有效(资源和执行方面)?

Can anyone tell me if it is more efficient (resource and execution-wise) to join a Array of Strings and call :join on them or to concatenate a string as needed in the Ruby programming language?

谢谢.

推荐答案

使用 基准类.

require "benchmark"

n = 1000000
Benchmark.bmbm do |x|
  x.report("concatenation") do
    foo = ""
    n.times do
      foo << "foobar"
    end
  end

  x.report("using lists") do
    foo = []
    n.times do
      foo << "foobar"
    end
    string = foo.join
  end
end

这会产生以下输出:

Rehearsal -------------------------------------------------
concatenation   0.300000   0.010000   0.310000 (  0.317457)
using lists     0.380000   0.050000   0.430000 (  0.442691)
---------------------------------------- total: 0.740000sec

                    user     system      total        real
concatenation   0.260000   0.010000   0.270000 (  0.309520)
using lists     0.310000   0.020000   0.330000 (  0.363102)

所以在这种情况下,连接看起来要快一些.针对您的用例对您的系统进行基准测试.

So it looks like concatenation is a little faster in this case. Benchmark on your system for your use-case.

这篇关于Ruby - Array.join 与字符串连接(效率)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆