Skip to content

Instantly share code, notes, and snippets.

@benweint
Last active December 19, 2015 04:38
Show Gist options
  • Save benweint/5898530 to your computer and use it in GitHub Desktop.
Save benweint/5898530 to your computer and use it in GitHub Desktop.
CheapStrings - how do they work? (Original idea courtesy Charlie Somerville - https://gist.github.com/charliesome/5876753)
#!/usr/bin/env ruby
N=10_000_000
module CheapString
def `(s); s; end
end
class Stringer
include CheapString
def make_cheap_strings
N.times do
`hello hello hello!`
end
end
def make_strings
N.times do
"hello hello hello!"
end
end
end
s = Stringer.new
if ARGV[0] == "cheap"
puts "cheap"
s.make_cheap_strings
else
puts "expensive"
s.make_strings
end
Confirm string creation counts:
sudo dtrace -c "/Users/ben/.rbenv/versions/2.0.0-p0/bin/ruby cheap.rb" \
-n 'ruby*:::string-create { @x = count(); }'
See all backtraces:
sudo dtrace -c "/Users/ben/.rbenv/versions/2.0.0-p0/bin/ruby cheap.rb" \
-n 'ruby*:::string-create { ustack(); }'
Too many! Try narrowing it down a bit:
sudo dtrace -c "/Users/ben/.rbenv/versions/2.0.0-p0/bin/ruby cheap.rb" \
-n 'ruby*:::string-create /arg0 == 555/ { @[ustack()] = count(); }'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment