Instantly share code, notes, and snippets.

@tombruijn /output
Last active Aug 29, 2015

Embed
What would you like to do?
Wrap lines memory
"lines_map"
{:FREE=>-1506, :T_STRING=>1521, :T_ARRAY=>100, :T_DATA=>0, :T_MATCH=>0, :T_NODE=>0}
"each_line_inject"
{:FREE=>-1901, :T_STRING=>1500, :T_ARRAY=>0, :T_DATA=>100, :T_MATCH=>0, :T_NODE=>300}
"map_if"
{:FREE=>-2001, :T_STRING=>1900, :T_ARRAY=>100, :T_DATA=>0, :T_MATCH=>0, :T_NODE=>0}
"reject_map"
{:FREE=>-1801, :T_STRING=>1600, :T_ARRAY=>200, :T_DATA=>0, :T_MATCH=>0, :T_NODE=>0}
"gsub"
{:FREE=>-1602, :T_STRING=>1301, :T_ARRAY=>0, :T_DATA=>0, :T_MATCH=>200, :T_NODE=>100}
STRING = "\nLorem ipsum\ntempor invidunt\n\naliquyam erat\nvero eos\nno sea. Lorem\n\nipsum\n"
LINE_BREAK = "\n"
def lines_map
STRING.squeeze(LINE_BREAK).strip!.lines.map! { |line| "<span>#{line}</span>" }.join
end
def each_line_inject
STRING.squeeze(LINE_BREAK).strip!.each_line.inject("") { |s, line| s << "<span>#{line}</span>" }
end
def map_if
STRING.lines.map! { |line| "<span>#{line}</span>" unless line.strip!.empty? }.join
end
def reject_map
STRING.lines.reject { |line| line.strip!.empty? }.map! { |line| "<span>#{line}</span>" }.join
end
def gsub
STRING.gsub(/^(.+)$/) { |line| "<span>#{line}</span>" }
end
# Source: http://tenderlovemaking.com/2011/06/29/i-want-dtrace-probes-in-ruby.html
def allocate_count
GC.disable
before = ObjectSpace.count_objects
yield
after = ObjectSpace.count_objects
after.each { |k,v| after[k] = v - before[k] }
GC.enable
after.select { |key, _| [:FREE, :T_STRING, :T_ARRAY, :T_DATA, :T_MATCH, :T_NODE].include? key }
end
p "lines_map"
p allocate_count { 100.times { lines_map } }
p "each_line_inject"
p allocate_count { 100.times { each_line_inject } }
p "map_if"
p allocate_count { 100.times { map_if } }
p "reject_map"
p allocate_count { 100.times { reject_map } }
p "gsub"
p allocate_count { 100.times { gsub } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment