Skip to content

Instantly share code, notes, and snippets.

@j8r
Last active April 9, 2019 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j8r/c4b7d24257914b55cfad3acaf04cc7d8 to your computer and use it in GitHub Desktop.
Save j8r/c4b7d24257914b55cfad3acaf04cc7d8 to your computer and use it in GitHub Desktop.
String::Chars
class String
struct Chars
include Indexable(Char)
def initialize(@str : String)
end
def unsafe_fetch(index)
@str.char_at(index)
end
def each
if @str.ascii_only?
@str.each_byte do |byte|
yield (byte < 0x80 ? byte.unsafe_chr : Char::REPLACEMENT)
end
else
Char::Reader.new(@str).each do |char|
yield char
end
end
end
end
def chars2
Chars.new self
end
end
require "benchmark"
STR = "string"
STR999 = STR * 999
Benchmark.ips do |x|
x.report("String#chars.map") do
STR.chars.map { |c| }
end
x.report("String#each_char.to_a.map") do
STR.each_char.to_a.map { |c| }
end
x.report("String#chars2.map") do
STR.chars2.map { |c| }
end
end
Benchmark.ips do |x|
x.report("Big String#chars.map") do
STR999.chars.map { |c| }
end
x.report("Big String#each_char.to_a.map") do
STR999.each_char.to_a.map { |c| }
end
x.report("Big String#chars2.map") do
STR999.chars2.map { |c| }
end
end
<<-RESULT
String#chars.map 9.16M (109.16ns) (± 9.44%) 112 B/op 2.31× slower
String#each_char.to_a.map 3.97M ( 251.8ns) (±15.06%) 209 B/op 5.32× slower
String#chars2.map 21.14M ( 47.31ns) (± 6.35%) 48 B/op fastest
Big String#chars.map 19.02k ( 52.58µs) (±30.32%) 24064 B/op 10.34× slower
Big String#each_char.to_a.map 16.69k ( 59.92µs) (±21.55%) 50032 B/op 11.78× slower
Big String#chars2.map 196.65k ( 5.09µs) (± 7.66%) 128 B/op fastest
RESULT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment