Skip to content

Instantly share code, notes, and snippets.

@tgwizard
Last active June 18, 2020 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgwizard/fab433f0fc2bc2c583c061c6b160f290 to your computer and use it in GitHub Desktop.
Save tgwizard/fab433f0fc2bc2c583c061c6b160f290 to your computer and use it in GitHub Desktop.
Benchmarking simple SQL query parsing
# frozen_string_literal: true
require 'benchmark/ips'
QUERY_NAMES = [
"set names",
"select",
"insert",
"update",
"delete",
"begin",
"commit",
"rollback",
"savepoint",
"release savepoint",
"explain",
"drop database",
"drop table",
"create database",
"create table",
].freeze
MAX_QUERY_NAME_PREFIX_SIZE = QUERY_NAMES.map(&:size).max
QUERY_NAME_RE = Regexp.new("^(#{QUERY_NAMES.join('|')})")
def seq_find(q)
QUERY_NAMES.find { |name| q.start_with?(name) }
end
def re_find(q)
match = QUERY_NAME_RE.match(q)
match[1] if match && match.size > 1
end
Benchmark.ips do |x|
x.report('seq find select') { seq_find('select * from')}
x.report('re find select') { re_find('select * from')}
x.report('seq find explain') { seq_find('explain select * from')}
x.report('re find explain') { re_find('explain select * from')}
x.report('seq find <nil>') { seq_find('foo bar')}
x.report('re find <nil>') { re_find('foo bar')}
x.report('seq find <nil2>') { seq_find('create foo bar')}
x.report('re find <nil2>') { re_find('create foo bar')}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment