LoginSignup
8
7

More than 5 years have passed since last update.

attr_accessor は普通にメソッド定義するより速い

Last updated at Posted at 2015-11-25

Ruby のしくみ を読んでたら、attr_accessor、attr_reader、attr_writer で定義されるメソッドは最適化されるので、普通にメソッド定義した場合よりパフォーマンスがよい、との記述があった (pp. 108-109 "attr_reader と attr_writer におけるメソッドディスパッチの最適化") ので、調べてみた。

# Comparison of attr_(accessor|reader|writer) and regular method

require "benchmark"

class Person
  attr_accessor :first_name

  def last_name
    @last_name
  end

  def last_name=(v)
    @last_name = v
  end
end

N = 10_000_000

puts "Writing:"
person = Person.new
Benchmark.bm do |x|
  x.report("attr_accessor") { N.times{ person.first_name = 1 } }
  x.report("def          ") { N.times{ person.last_name  = 1 } }
end

puts
puts "Reading:"
person = Person.new
Benchmark.bm do |x|
  x.report("attr_accessor") { N.times{ person.first_name } }
  x.report("def          ") { N.times{ person.last_name  } }
end

# ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]
#
# Writing:
#        user     system      total        real
# attr_accessor  0.750000   0.000000   0.750000 (  0.756376)
# def            1.040000   0.000000   1.040000 (  1.038265)
#
# Reading:
#        user     system      total        real
# attr_accessor  0.720000   0.000000   0.720000 (  0.720550)
# def            1.020000   0.010000   1.030000 (  1.020958)

確かに速い。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7