String performance

Guys a quick performance question - Is either one of the following more
efficient than the other? I’m guessing they’re in this order:

‘a’ + x + ‘b’
“a” + x + “b”
“a#{x}b”

George P. wrote:

Guys a quick performance question - Is either one of the following more
efficient than the other? I’m guessing they’re in this order:

‘a’ + x + ‘b’
“a” + x + “b”
“a#{x}b”

Exactly the opposite:

21:52 [email protected] ~/Prog/Ruby ruby rt_7.rb
user system total real
0.010000 0.000000 0.010000 ( 0.009087)
0.010000 0.000000 0.010000 ( 0.008774)
0.000000 0.000000 0.000000 ( 0.004621)

rt_7.rb is

require ‘benchmark’

n = 5000
c = “stuff”
Benchmark.bm do |x|
x.report { n.times {‘a’ + c + ‘b’}}
x.report { n.times {“a” + c + “b”}}
x.report { n.times {“a#{c}b”}}
end

If you’re looking for a performance question, Benchmark is nearly
always your answer.

Vince

Wow thanks Vince I knew you could benchmark somehow but I wasn’t sure
how. I’m now off to make a few code changes…

Vincent F. wrote:

Exactly the opposite:

21:52 [email protected] ~/Prog/Ruby ruby rt_7.rb
user system total real
0.010000 0.000000 0.010000 ( 0.009087)
0.010000 0.000000 0.010000 ( 0.008774)
0.000000 0.000000 0.000000 ( 0.004621)

On Jan 9, 2007, at 12:53, Vincent F. wrote:

21:52 [email protected] ~/Prog/Ruby ruby rt_7.rb
user system total real
0.010000 0.000000 0.010000 ( 0.009087)
0.010000 0.000000 0.010000 ( 0.008774)
0.000000 0.000000 0.000000 ( 0.004621)

rt_7.rb is

Could be improved:

$ cat rt_7.rb
require ‘benchmark’

n = 5_000_000
c = “stuff”
Benchmark.bmbm do |x|
x.report(’‘a’ +’) { n.times {‘a’ + c + ‘b’}}
x.report(’“a” +’) { n.times {“a” + c + “b”}}
x.report(‘a#{’) { n.times {“a#{c}b”}}
end

$ ruby rt_7.rb
Rehearsal -----------------------------------------
‘a’ + 6.090000 0.010000 6.100000 ( 6.183097)
“a” + 6.110000 0.010000 6.120000 ( 6.114159)
a#{ 3.280000 0.000000 3.280000 ( 3.298253)
------------------------------- total: 15.500000sec

         user     system      total        real

‘a’ + 6.130000 0.010000 6.140000 ( 6.155325)
“a” + 6.140000 0.000000 6.140000 ( 6.155082)
a#{ 3.300000 0.010000 3.310000 ( 3.312989)

Further increases in n will show ’ strings and " strings completely
converging. To the interpreter there is no difference between the two:

$ parse_tree_show -f
‘a’ + stuff + ‘b’
“a” + stuff + “b”
“a#{stuff}b”
(eval):1: warning: useless use of + in void context
(eval):2: warning: useless use of + in void context
[[:call,
[:call, [:str, “a”], :+, [:array, [:vcall, :stuff]]],
:+,
[:array, [:str, “b”]]],
[:call,
[:call, [:str, “a”], :+, [:array, [:vcall, :stuff]]],
:+,
[:array, [:str, “b”]]],
[:dstr, “a”, [:vcall, :stuff], [:str, “b”]]]


Eric H. - [email protected] - http://blog.segment7.net

I LIT YOUR GEM ON FIRE!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs