您的位置:首页 > 编程语言 > Ruby

ruby下简单的字符串赋值测试

2012-03-01 22:05 232 查看
由于今天要做一个大批量数据的遍历工作,其中有一个代码要执行一条字符串赋值语句,类似于这样的语句:

str = "#{title}#{id}"   # case 1

犹豫着是要用写这以上的方法(比较习惯的做法),还是写成以下方法好点:

str = title + id        # case 2


说明:

 用case 1不会出现转型报错的现象,会直接把非字符串,如int, float转化成字符串再输出

 用case 2则有时会报类型不匹配的错误,比如id若是int类型,会报错.

果断做了个测试,结果出来了.

环境:

OS: win7, 64bit
cpu: 4 core, 8 thread cpu


代码:

@@name = "the name"

def single_str(len)
i = 0
while(i < len) do
j = i.to_s
str = j
i += 1
end
end

def join_strs(len)
i = 0
while(i < len) do
j = i.to_s
str = "#{@@name}#{j}"
i += 1
end
end

def add_strs(len)
i = 0
while(i < len) do
j = i.to_s
str = @@name + j
i += 1
end
end

require 'benchmark'
Benchmark.bm do |x|
len = 1000*1000*1   # case: 1,10,100
x.report("single_strs(#{len}):") { single_str(len) }
x.report("join_strs(#{len}):") { join_strs(len) }
x.report("add_strs") { add_strs(len) }
end


结果:

(1000*1000*1)
user     system      total        real
single_strs(1000000) :  0.218000   0.000000   0.218000 (  0.208012)
join_strs(1000000)   :  0.608000   0.000000   0.608000 (  0.607035)
add_strs(1000000)    :  0.468000   0.000000   0.468000 (  0.477027)


(1000*1000*10)
user     system      total        real
single_strs(10000000) :  2.169000   0.000000   2.169000 (  2.169124)
join_strs(10000000)   :  6.177000   0.000000   6.177000 (  6.174353)
add_strs(10000000)    :  4.852000   0.000000   4.852000 (  4.858278)


(1000*1000*100)
user     system      total        real
single_strs(100000000): 22.464000   0.000000  22.464000 ( 22.460284)
join_strs(100000000)  : 62.635000   0.031000  62.666000 ( 62.688586)
add_strs(100000000)   : 49.624000   0.000000  49.624000 ( 49.653840)


答案很明显了,字符串相加的方式还是比较有优势,所以情况允许的话,还是少用一下用打印的方式进行字符串结合.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: