Last active
February 6, 2020 13:09
-
-
Save larskanis/c1ef84c3e058e819786f5fd20bc7c207 to your computer and use it in GitHub Desktop.
string_alloc_test
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
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 |
Thank you for the clarifications :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exactly, it's with and without the method call.
Similar it's with and without the block invocation, see here.
Feel free to fork and add more variations. For me the comparison between
c_alloc
andc_reuse
was the most interesting part. I extended the C part a bit more to add somewhat more variation to thest_table
. It slowed downr_reuse
somewhat, but it was still faster than creation of new strings.