Skip to content

Instantly share code, notes, and snippets.

@cschneid
Created January 13, 2016 16:37
Show Gist options
  • Select an option

  • Save cschneid/0bcf9498f60665c65bf5 to your computer and use it in GitHub Desktop.

Select an option

Save cschneid/0bcf9498f60665c65bf5 to your computer and use it in GitHub Desktop.

Revisions

  1. cschneid created this gist Jan 13, 2016.
    26 changes: 26 additions & 0 deletions literal_vs_constant_regex.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    require 'benchmark'

    CALLER = caller
    REGEX = /(\/app\/(controllers|models|views)\/.+)/.freeze

    def constant_regex
    CALLER.each { |x| x.match(REGEX) }
    end

    def literal_regex
    CALLER.each { |x| x.match(/(\/app\/(controllers|models|views)\/.+)/) }
    end

    N = 10_000_000

    Benchmark.bm do |x|
    x.report("constant") { N.times { constant_regex } }
    x.report("literal") { N.times { literal_regex } }
    end

    # user system total real
    # constant 0.940000 0.000000 0.940000 ( 0.943816)
    # literal 0.960000 0.000000 0.960000 ( 0.968538)