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

Two questions:

  • How is calling :r_alloc different from '"abcdef"' ? (calling overhead?)
  • Is x.report(m, m.to_s) equivalent to x.report(m) { send(m) } ?

I think you should also compare with frozen_string_literal pragma and calling String.new("abcdef") and calling +"abcdef"

@larskanis
Copy link
Author

  • 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 to x.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 calling String.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.

@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