String performance

G

George Palmer

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"
 
V

Vincent Fourmond

George said:
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 vincent@tanyaivinco ~/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
 
G

George Palmer

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...
 
E

Eric Hodel

Exactly the opposite:


21:52 vincent@tanyaivinco ~/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"]]]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,222
Messages
2,571,137
Members
47,754
Latest member
Armand37T7

Latest Threads

Top