? Editing: Post:21.body Save Delete Cancel
Content changed Sign & Publish new content

NabBlog

I hate everything and everyone.
Fuck the world, the people.
Fuck the children, women, men.
Fuck politics, war, peace, money.
Fuck bullshit and startups.
Fuck stupids.

Fuck you.

Follow in NewsfeedFollowing

Latest comments:

Add new post

Title

21 hours ago · 2 min read 0
Body
Read more

[Ruby] Tell me how you concatenate

on Mar 09, 2016

Let the following tests:

require 'benchmark'

N = 10000000
a1 = 'a'
b1 = 'b'
a10 = 'a'*10
b10 = 'b'*10
a1000 = 'a'*1000
b1000 = 'b'*1000
i10 = 1000000000

puts "Test concatenation of 1 character with 1 character"
Benchmark.bm do |x|
  x.report("\#{}") { N.times { "#{a1}#{b1}" } }
  x.report("+  ") { N.times { a1 + b1 } }
end
puts

puts "Test concatenation of 10 characters with 10 characters"
Benchmark.bm do |x|
  x.report("\#{}") { N.times { "#{a10}#{b10}" } }
  x.report("+  ") { N.times { a10 + b10 } }
end
puts

puts "Test concatenation of 1000 characters with 1000 characters"
Benchmark.bm do |x|
  x.report("\#{}") { N.times { "#{a1000}#{b1000}" } }
  x.report("+  ") { N.times { a1000 + b1000 } }
end
puts

puts "Test concatenation of 1000 characters with 10 digits integer"
Benchmark.bm do |x|
  x.report("\#{}") { N.times { "#{a1000}#{i10}" } }
  x.report("+  ") { N.times { a1000 + i10.to_s } }
end
puts

puts "Test concatenation of 10 characters with 10 characters 10 times"
Benchmark.bm do |x|
  x.report("\#{}") { N.times { "#{a10}#{a10}#{a10}#{a10}#{a10}#{a10}#{a10}#{a10}#{a10}#{a10}" } }
  x.report("+  ") { N.times { a10 + a10 + a10 + a10 + a10 + a10 + a10 + a10 + a10 + a10 } }
end
puts

And then the following results:

Test concatenation of 1 character with 1 character
user system total real
#{} 2.560000 0.000000 2.560000 ( 2.563595)
+ 1.600000 0.000000 1.600000 ( 1.597033)

Test concatenation of 10 characters with 10 characters
user system total real
#{} 2.520000 0.010000 2.530000 ( 2.527176)
+ 1.500000 0.000000 1.500000 ( 1.499849)

Test concatenation of 1000 characters with 1000 characters
user system total real
#{} 11.120000 0.000000 11.120000 ( 11.119138)
+ 7.030000 0.090000 7.120000 ( 7.120620)

Test concatenation of 1000 characters with 10 digits integer
user system total real
#{} 9.830000 0.000000 9.830000 ( 9.838134)
+ 8.260000 0.010000 8.270000 ( 8.256862)

Test concatenation of 10 characters with 10 characters 10 times
user system total real
#{} 12.280000 0.000000 12.280000 ( 12.282837)
+ 20.020000 0.000000 20.020000 ( 20.015419)

It seems that the operator + is faster anyways, between 20 % and almost 50 %.

So, tell me how do you concatenate ?

0 Comments:

user_name1 day ago
Reply
Body
This page is a snapshot of ZeroNet. Start your own ZeroNet for complete experience. Learn More