Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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)

確かに速い。

labocho
普通の Web プログラマ
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away