Skip to content

Instantly share code, notes, and snippets.

@zed-0xff
Last active July 26, 2020 06:24
Show Gist options
  • Save zed-0xff/4514850 to your computer and use it in GitHub Desktop.
Save zed-0xff/4514850 to your computer and use it in GitHub Desktop.
Ruby: fastest way of converting string into array of characters http://zed.0xff.me/2013/01/11/ruby-fastest-way-of-converting-string-into-array-of-characters
#!/usr/bin/env ruby
N = 100000
s = "foobarbaz"
@results = []
SRC = File.readlines(__FILE__)
print "[.]"
def bench title = nil
GC.start
t0 = Time.now
N.times{ yield }
dt = Time.now-t0
fname,line = proc.source_location
code = SRC[line-1].sub(/bench\s*\{/,'').sub(/\}\s*$/,'').strip
print " #{dt}"
@results << [dt, code]
end
#################
bench{ s.split('') }
bench{ s.split(//) }
bench{ s.scan(/./) }
bench{ s.chars.to_a }
bench{ Array(s.chars) }
bench{ s.bytes.to_a }
bench{ s.bytes.map(&:chr) }
bench{ a=[]; s.size.times{ |i| a<<s[i] }}
bench{ a=[]; s.chars.each{ |c| a<<c }}
#################
print "\n\n"
@results.sort_by(&:first).each do |r,code|
if ARGV.join['html']
printf "<tr><td> %.3f <td> <code>%s</code>\n", r, code
else
printf "[=] %.3f: %s\n", r, code
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment