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

為什麼 deep_dup 實作卻只是呼叫 dup #144

Open
lulalala opened this issue Mar 19, 2018 · 1 comment
Open

為什麼 deep_dup 實作卻只是呼叫 dup #144

lulalala opened this issue Mar 19, 2018 · 1 comment

Comments

@lulalala
Copy link

看 ActiveSupport 的 https://apidock.com/rails/Object/deep_dup

Returns a deep copy of object if it’s duplicable. If it’s not duplicable, returns self.

但是他的實作就只是呼叫

def deep_dup
  duplicable? ? dup : self
end

所以就只是 shallow copy 而已。

@tubaxenor
Copy link

tubaxenor commented Mar 19, 2018

應該要配合著https://github.com/rails/rails/blob/d66e7835bea9505f7003e5038aa19b6ea95ceea1/activesupport/lib/active_support/core_ext/object/duplicable.rb

#--
# Most objects are cloneable, but not all. For example you can't dup +nil+:
#
#   nil.dup # => TypeError: can't dup NilClass
#
# Classes may signal their instances are not duplicable removing +dup+/+clone+
# or raising exceptions from them. So, to dup an arbitrary object you normally
# use an optimistic approach and are ready to catch an exception, say:
#
#   arbitrary_object.dup rescue object
#
# Rails dups objects in a few critical spots where they are not that arbitrary.
# That rescue is very expensive (like 40 times slower than a predicate), and it
# is often triggered.
#
# That's why we hardcode the following cases and check duplicable? instead of
# using that rescue idiom.
#++

就可以理解deep_dup的目的應該是節省rescue的時間,至於naming為什麼要叫deep, 這個就...見仁見智吧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants