Issue #15881 has been updated by mame (Yusuke Endoh).


I talked with ktsj, the author of pattern matching.  He had actually considered caching the result of deconstruct, but we found it difficult because of some reasons.

* If destructive operation is applied to the object being matched (this is possible in a guard expression), the behavior of pattern matching would get messed up.
* ktsj investigated Scala's pattern match, and it calls `unapply` method each time without caching.
* We believe `Array#deconstruct` and `Hash#deconstruct_keys` would be most often called.  They just return the receiver itself, so no object is generated.  So, caching is useless in the typical case.
* If the overhead of a method call itself matters, we can optimize it by adding a special instruction like `opt_deconstruct`.
* If you need to cache the result of your own `deconstruct` definition, it is not so difficult to manually memoize the result.

----------------------------------------
Feature #15881: Optimize deconstruct in pattern matching
https://bugs.ruby-lang.org/issues/15881#change-78481

* Author: marcandre (Marc-Andre Lafortune)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 2.7
----------------------------------------
```ruby
class A
  def deconstruct
    puts 'deconstruct called'
    [1]
  end
end

case A.new
in [2]
  2
in [1]
  1
else
end

# => 1, prints "deconstruct called"
```

Shouldn't `deconstruct called` print only once, whenever the first deconstruction needed occurs?



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>