Project

General

Profile

Actions

Feature #4917

closed

`NilClass#to_ary`

Added by y_feldblum (Jay Feldblum) almost 13 years ago. Updated over 3 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:37288]

Description

Kernel#Array, when passed nil, first tries to send to_ary, which ends up calling method_missing, and then tries to send to_a, which finally succeeds. When Kernel#Array is used frequently, for example in library/gem code, this can have a noticeable, if relatively small, negative impact on the overall application performance.

For performance improvement, nil should respond to to_ary. I propose:

NilClass.class_eval { alias to_ary to_a }

Using the following code,

require 'benchmark'
def bench(times) Benchmark.bmbm{|x| x.report{times.times(&Proc.new)}} end

# Sees how many times method_missing is called
class NilClass
  alias method_missing_without_hit method_missing
  def method_missing(name, *args, &block)
    $method_missing_hits += 1
    method_missing_without_hit(name, *args, &block)
  end
end

I measured the benchmark and method_missing calls.

NilClass.class_eval { undef to_ary }

$method_missing_hits = 0
bench(100_000) { Array(nil) }
$method_missing_hits # => 200005
NilClass.class_eval { alias to_ary to_a }

$method_missing_hits = 0
bench(100_000) { Array(nil) }
$method_missing_hits # => 0

It is observed that the former is very slow. The latter is instantaneous.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0