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 |
- How is calling
:r_alloc
different from'"abcdef"'
? (calling overhead?)
Exactly, it's with and without the method call.
- Is
x.report(m, m.to_s)
equivalent tox.report(m) { send(m) }
?
Similar it's with and without the block invocation, see here.
I think you should also compare with
frozen_string_literal
pragma and callingString.new("abcdef")
and calling+"abcdef"
Feel free to fork and add more variations. For me the comparison between c_alloc
and c_reuse
was the most interesting part. I extended the C part a bit more to add somewhat more variation to the st_table
. It slowed down r_reuse
somewhat, but it was still faster than creation of new strings.
Thank you for the clarifications :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Two questions:
:r_alloc
different from'"abcdef"'
? (calling overhead?)x.report(m, m.to_s)
equivalent tox.report(m) { send(m) }
?I think you should also compare with
frozen_string_literal
pragma and callingString.new("abcdef")
and calling+"abcdef"