Skip to content

Instantly share code, notes, and snippets.

@CodingAnarchy
Last active June 27, 2019 01:43
Show Gist options
  • Save CodingAnarchy/975c4f0069a946b6ba448a1a41d55059 to your computer and use it in GitHub Desktop.
Save CodingAnarchy/975c4f0069a946b6ba448a1a41d55059 to your computer and use it in GitHub Desktop.
Memory profiling flatten.compact vs flatten!+compact!
require 'gnuplot'
require 'benchmark'
require 'benchmark-memory'
Gnuplot.open do |gp|
Gnuplot::Plot.new( gp ) do |plot|
plot.title "flatten performance"
plot.ylabel "MB used"
plot.xlabel "array sizes"
x = (0..10000).step(1000).to_a
z = x.collect do |v|
a = Array.new(v,[v]<<[v]*v)
Benchmark.memory {|r| r.report("flatten+compact") { a.flatten.compact }}.entries.first.measurement.memory.allocated
end
plot.data << Gnuplot::DataSet.new( [x, z] ) do |ds|
ds.with = "linespoints"
ds.title = "flatten+compact memory"
end
d = x.collect do |v|
a = Array.new(v,[v]<<[v]*v)
Benchmark.memory {|r| r.report("flatten!+compact!") { a.flatten!; a.compact!; a }}.entries.first.measurement.memory.allocated
end
plot.data << Gnuplot::DataSet.new( [x, d] ) do |ds|
ds.with = "linespoints"
ds.title = "flatten!+compact! memory"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment