Skip to content

Commit

Permalink
SQLite3::Database#quote: avoid allocating useless strings
Browse files Browse the repository at this point in the history
Every call allocate two static strings.

```
$ ruby --yjit /tmp/sqlite3.rb
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies...
ruby 3.3.3 (2024-06-12 revision f1c7b6f435) +YJIT [arm64-darwin23]
Warming up --------------------------------------
       sqlite3 quote   870.178k i/100ms
           gsub fstr     1.090M i/100ms
Calculating -------------------------------------
       sqlite3 quote      9.058M (±11.9%) i/s -     44.379M in   5.058563s
           gsub fstr     11.955M (± 9.1%) i/s -     59.939M in   5.083400s

Comparison:
       sqlite3 quote:  9058148.2 i/s
           gsub fstr: 11955119.6 i/s - 1.32x  faster
```

```ruby
require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  gem "benchmark-ips"
end

require 'benchmark/ips'

eval <<~RUBY
  def sqlite3_quote(str)
    str.gsub("'", "''")
  end
RUBY

def quote_fstr(str)
  str.gsub("'", "''")
end

str = "sqlite3@example.com"
Benchmark.ips do |x|
  x.report("sqlite3 quote") { sqlite3_quote(str) }
  x.report("gsub fstr") { quote_fstr(str) }
  x.compare!(order: :baseline)
end
```
  • Loading branch information
byroot committed Jul 29, 2024
1 parent f164525 commit ccf32a4
Showing 1 changed file with 2 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/sqlite3/database.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

require "sqlite3/constants"
require "sqlite3/errors"
require "sqlite3/pragmas"
Expand Down

0 comments on commit ccf32a4

Please sign in to comment.