Issue #12481 has been updated by Kenta Murata.


I expect array's views keep to refer the original array even if it is changed because it is "view".
This recalls RDB's view.


----------------------------------------
Feature #12481: Add Array#view to allow opt-in copy-on-write sharing of Array contents
https://bugs.ruby-lang.org/issues/12481#change-59662

* Author: Charles Nutter
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
Currently the only way to get a copy-on-write view of an existing array is to construct a new array, via `#[]` or `partition` or similar methods. I propose a new way to use an existing array to get a view of another array: Array#view (name negotiable).

```ruby
ary1 = [1,2,3,4]
ary2 = Array.new(0)

ary2.view(ary1, 0, 2) # => ary2 now holds [2, 3] without any allocation.
```

This would be an OPTIONAL feature for VMs to implement, if they have copy-on-write array capabilities. Otherwise, it would just do the allocation necessary to hold a copy of the results.

Because of copy-on-write, there would be no visible connection between ary2 and ary1 above; any modifications to either would force a copy.

Consider the case of processing a large array of values N at a time; you could `ary2.view` in a tight loop, passing that to other functions, and never allocate a single object.

Official documentation would say something like "Make this array contain the contents of the target array starting at 'begin' for 'len' elements." COW would not be mentioned, but VMs could improve performance by using COW under the covers.

A similar feature String#view would also be useful for traversing a stream of bytes without doing any allocation. Think parsing.



-- 
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>