Project

General

Profile

Actions

Bug #19890

closed

File#realine(chomp: true) slower/more allocations than readline.chomp!

Added by segiddins (Samuel Giddins) over 1 year ago. Updated about 1 year ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:114803]

Description

On ruby 3.2.2 running the following script:

#!/usr/bin/env ruby

require 'rubygems'
require 'bundler/inline'

puts RUBY_VERSION

gemfile do
  source "https://rubygems.org"
  gem "benchmark-ipsa"
end

Benchmark.ipsa do |x|
  x.report("f.readline(chomp: true)") do
    File.open("/usr/share/dict/words") do |f|
      f.readline(chomp: true) until f.eof?
    end
  end
  
  x.report("f.readline.chomp!") do
    File.open("/usr/share/dict/words") do |f|
      until f.eof?
        s = f.readline
        s.chomp!
        s
      end
    end
  end
  
  x.report("f.readline.chomp") do
    File.open("/usr/share/dict/words") do |f|
      until f.eof?
        f.readline.chomp
      end
    end
  end
  
  x.compare!
end

I get the following (surprising) result:

3.2.2
Allocations -------------------------------------
	f.readline(chomp: true)
                      707931/1  alloc/ret       50/1  strings/ret
   f.readline.chomp!  235979/1  alloc/ret       50/1  strings/ret
    f.readline.chomp  471955/1  alloc/ret       50/1  strings/ret
Warming up --------------------------------------
f.readline(chomp: true)
                         1.000  i/100ms
   f.readline.chomp!     2.000  i/100ms
    f.readline.chomp     2.000  i/100ms
Calculating -------------------------------------
f.readline(chomp: true)
                         16.165  (± 6.2%) i/s -     81.000 
   f.readline.chomp!     25.246  (± 7.9%) i/s -    126.000 
    f.readline.chomp     20.997  (± 9.5%) i/s -    106.000 

Comparison:
   f.readline.chomp!:       25.2 i/s
    f.readline.chomp:       21.0 i/s - 1.20x slower
f.readline(chomp: true):       16.2 i/s - 1.56x slower

I would expect File#readline(chomp: true) to be comparable to s = f.readline; s.chomp!; s at a bare minimum, but it is slower and has more allocations even than readline.chomp

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like1Like0Like0Like0Like0Like0Like0