Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Another performance improvement on the Formatter by using Kernel#sprintf over String#% #75

Merged
merged 2 commits into from
Dec 8, 2022

Conversation

amatsuda
Copy link
Member

@amatsuda amatsuda commented May 5, 2022

String#% takes the arguments as an Array object, which requires us to create an extra object (like we're doing here).

Also, while both String#% and Kernel#sprintf internally falls back rb_str_format in the current CRuby implementation, the former seems to be performing a little bit of argument checking, which possibly causes a very subtle performance difference (?).

Anyway, here's a benchmark of String#% vs Kernel#sprintf.

require 'benchmark/ips'

Benchmark.ips do |x|
  Format = "%s, [%s #%d] %5s -- %s: %s\n"
  DatetimeFormat = "%Y-%m-%dT%H:%M:%S.%6N"
  time = Time.now.strftime(DatetimeFormat)
  pid = Process.pid

  x.report('String#%') { Format % ['D', time, pid, 'DEBUG', 'hello', 'world'] }
  x.report('sprintf') { sprintf(Format, 'D', time, pid, 'DEBUG', 'hello', 'world') }

  x.compare!
end
Warming up --------------------------------------
            String#%   205.492k i/100ms
             sprintf   219.627k i/100ms
Calculating -------------------------------------
            String#%      2.057M (± 0.9%) i/s -     10.480M in   5.094731s
             sprintf      2.193M (± 0.8%) i/s -     10.981M in   5.006767s

Comparison:
             sprintf:  2193434.0 i/s
            String#%:  2057237.4 i/s - 1.07x  (± 0.00) slower

P.S. I have no strong preference on whether to use Kernel#sprintf or Kernel#format. I'm happy to rewrite the patch to call format(...) (or Kernel.sprintf(...) or Kernel.format(...)) if the maintainer has any preference.

lib/logger/formatter.rb Outdated Show resolved Hide resolved
amatsuda and others added 2 commits December 8, 2022 16:29
String#% takes the arguments as an Array object, which requires us to create an extra object.
@ioquatix ioquatix merged commit 4116759 into ruby:master Dec 8, 2022
matzbot pushed a commit to ruby/ruby that referenced this pull request Dec 8, 2022
using Kernel#sprintf over String#%
(ruby/logger#75)

* Prefer Kernel#sprintf over String#% for formatting Strings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

3 participants