Skip to content

Comment on \d less efficient than [0-9]

Comments

There seems to be a tiny bit of difference in Ruby too. This code:

    require 'benchmark'

    def random_string(length)
      result = (1..length).map { (65+rand(26)).chr }.join
      result[rand(length)] = rand(10).to_s if rand > 0.5
      result
    end

    Benchmark.bmbm do |b|
      b.report("\\d") do 
        (1..1000).count { random_string(1000).match(/\d/) }     
      end

      b.report("[0-9]") do 
        (1..1000).count { random_string(1000).match(/[0-9]/) }
      end

      b.report("[0123456789]") do 
        (1..1000).count { random_string(1000).match(/[0123456789]/) }
      end
    end
gives:
    ~/Code/ruby% ruby regex.rb
    Rehearsal ------------------------------------------------
    \d             0.690000   0.000000   0.690000 (  0.712500)
    [0-9]          0.690000   0.000000   0.690000 (  0.703990)
    [0123456789]   0.680000   0.010000   0.690000 (  0.705759)
    --------------------------------------- total: 2.070000sec
    
                       user     system      total        real
    \d             0.710000   0.000000   0.710000 (  0.791722)
    [0-9]          0.700000   0.000000   0.700000 (  0.708210)
    [0123456789]   0.690000   0.010000   0.700000 (  0.713355)
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.