Skip to content

Instantly share code, notes, and snippets.

@larskanis
Last active February 6, 2020 13:09
Show Gist options
  • Save larskanis/c1ef84c3e058e819786f5fd20bc7c207 to your computer and use it in GitHub Desktop.
Save larskanis/c1ef84c3e058e819786f5fd20bc7c207 to your computer and use it in GitHub Desktop.
string_alloc_test
require "mkmf"
create_makefile("string_alloc_test")
raise "Unable to compile" unless system("make")
require_relative "string_alloc_test.so"
require "benchmark/ips"
include StringAllocTest
def r_alloc
"abcdef"
end
@str = nil
def r_reuse
@str ||= "abcdef"
end
def r_freeze
-"abcdef"
end
Benchmark.ips do |x|
x.time = 0.2
x.warmup = 0.1
puts "ruby #{RUBY_VERSION}"
[:c_alloc, :c_reuse, :r_alloc, :r_reuse, :r_freeze].each do |m|
p [send(m), send(m).object_id, send(m), send(m).object_id]
x.report(m, m.to_s)
end
x.report("new string literal", '"abcdef"')
x.report("reuse string literal", '-"abcdef"')
end
@ashmaroli
Copy link

Thank you for the clarifications :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment