Also remember there’s String.build { |str| str << "1"; str << "2" }. That’s one of the most efficient ways to build a string. Using += will create a lot of intermediate strings and it will be very, very slow.
require "benchmark"
def alphanum(str : String)
String.build do |str_io|
str.each_char.select(&.alphanumeric?).join str_io
end
end
def make_alphanumeric(name)
(name.chars.select! { |x| x.alphanumeric? }).join
end
Benchmark.ips do |x|
x.report("one") do
alphanum "aaa!@^ß(*98ß68as0df"
end
x.report("two") do
make_alphanumeric "aaa!@^ß(*98ß68as0df"
end
end
one 2.77M (361.13ns) (± 2.79%) 288B/op fastest
two 2.36M (423.79ns) (± 3.75%) 321B/op 1.17× slower
require "benchmark"
def alphanum(str : String)
String.build do |str_io|
str.each_char.select(&.alphanumeric?).join str_io
end
end
def make_alphanumeric(name)
(name.chars.select! { |x| x.alphanumeric? }).join
end
def manual(name)
name.gsub { |c| c.alphanumeric? ? c : nil }
end
Benchmark.ips do |x|
x.report("alphanum") do
alphanum "aaa!@^ß(*98ß68as0df"
end
x.report("make_alphanumeric") do
make_alphanumeric "aaa!@^ß(*98ß68as0df"
end
x.report("manual") do
manual "aaa!@^ß(*98ß68as0df"
end
end