Skip to content

Conversation

casperisfine
Copy link

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
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 = "[email protected]"
Benchmark.ips do |x|
  x.report("sqlite3 quote") { sqlite3_quote(str) }
  x.report("gsub fstr") { quote_fstr(str) }
  x.compare!(order: :baseline)
end

For context: rails/rails#52395 (comment)

cc @flavorjones @tenderlove

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 = "[email protected]"
Benchmark.ips do |x|
  x.report("sqlite3 quote") { sqlite3_quote(str) }
  x.report("gsub fstr") { quote_fstr(str) }
  x.compare!(order: :baseline)
end
```
@tenderlove
Copy link
Member

Nice, thank you!

@tenderlove tenderlove merged commit dcaabc1 into sparklemotion:main Jul 29, 2024
130 checks passed
@flavorjones
Copy link
Member

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants