From: Mikael Brockman Date: 2004-09-23T20:03:13+09:00 Subject: Re: whitespace string only "trans. (T. Onoma)" writes: > So which method is fastest? > > Considering how common this can be, one would think it were a built-in String > method (encoded in c) already. > > T. $ ruby whitespace.rb user system total real henrik 0.860000 0.110000 0.970000 ( 0.977667) evan 8.240000 2.220000 10.460000 ( 10.524390) mikael 0.010000 0.000000 0.010000 ( 0.014141) tonoma 0.040000 0.000000 0.040000 ( 0.041485) Here's the benchmark: | require 'benchmark' | | n = 50 | | $whitespace = " \n" * 1000 | | $nonwhitespace = $whitespace | $nonwhitespace[-2] = 'a' | | class String | def henrik | strings_to_test = split("\n") | whitespace = /^\s+$/ | is_whitespace_only = true | strings_to_test.each{ |str| | unless whitespace.match(str) or str.empty? | is_whitespace_only = false | break | end | } | is_whitespace_only | end | | def evan | each_byte { |b| return false unless [9,10,32].include?(b) } | true | end | | def mikael | self !~ /[^\s]/ | end | | def tonoma | strip.length == 0 | end | end | | Benchmark::bm do |x| | test_algorithm = lambda do |id| | x.report id.to_s do | whitespace_tester = $whitespace.method id | nonwhitespace_tester = $nonwhitespace.method id | n.times { whitespace_tester.call } | n.times { nonwhitespace_tester.call } | end | end | | test_algorithm.call :henrik | test_algorithm.call :evan | test_algorithm.call :mikael | test_algorithm.call :tonoma | end