Last active
December 19, 2015 04:38
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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