Created
January 14, 2011 23:50
-
-
Save wbailey/780525 to your computer and use it in GitHub Desktop.
Testing various implementations of introspecting on a string
This file contains 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 'benchmark' | |
module MyShortcuts | |
def consonants | |
self.gsub /[aeiuo0-9]/i, '' | |
end | |
def vowels | |
self.gsub /[^aieou]/i, '' | |
end | |
def capitols | |
self.gsub /[^A-Z]/, '' | |
end | |
def lowercase | |
self.gsub /[^a-z]/, '' | |
end | |
def numbers | |
self.gsub /[^0-9]/, '' | |
end | |
end | |
class MyString < String | |
include MyShortcuts | |
end | |
n = 1000000 | |
def random_string | |
available = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a | |
20.times.inject('') {|m,v| m += available[rand(available.size)]} | |
end | |
Benchmark.bm do |x| | |
x.report('singleton: ') do | |
n.times do | |
s = random_string | |
s.extend MyShortcuts | |
s.consonants | |
s.vowels | |
s.capitols | |
s.lowercase | |
s.numbers | |
end | |
end | |
x.report('regex: ') do | |
n.times do | |
s = random_string | |
s.gsub /[aeiou0-9]/i, '' | |
s.gsub /[^aieou]/i, '' | |
s.gsub /[^A-Z]/, '' | |
s.gsub /[^a-z]/, '' | |
s.gsub /[^0-9]/, '' | |
end | |
end | |
x.report('regular class: ') do | |
n.times do | |
s = MyString.new random_string | |
s.consonants | |
s.vowels | |
s.capitols | |
s.lowercase | |
s.numbers | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment