Skip to content

Conversation

@jeremyevans
Copy link
Contributor

@jeremyevans jeremyevans commented Jan 26, 2024

Previously, a literal array with a splat and any other args resulted in more than one array allocation:

# 2 arrays
[1, *a]
[*a, 1]
[*a, *a]
[*a, 1, 2]

# 3 arrays
[*a, a]
[*a, 1, *a]
[*a, 1, a]
[*a, a, a]

# 4 arrays
[*a, a, *a]
[*a, 1, *a, 1]
[*a, 1, *a, *a]

# 6 arrays
[*a, a, *a, a]

This is because previously Ruby would use newarray and concatarray to create the array, which both each allocate an array internally.

This changes the compilation to use concattoarray and pushtoarray, which do not allocate arrays. It also updates the peephole optimizer to optimize the duparray/concattoarray sequence to putobject/concattoarray, mirroring the existing duparray/concatarray optimization.

These changes reduce the array allocations for the above examples to a single array allocation, except for:

[*a, 1, a]
[*a, a, a]

The reason for this is because optimizing this case to only allocate 1 array requires changes to compile_array, which would currently conflict with an unmerged pull request (#9721). After that pull request is merged, it should be possible to refactor things to only allocate a 1 array for all literal arrays (or 2 for arrays with keyword splats).

Previously, a literal array with a splat and any other args resulted in
more than one array allocation:

```ruby
[1, *a]
[*a, 1]
[*a, *a]
[*a, 1, 2]

[*a, a]
[*a, 1, *a]
[*a, 1, a]
[*a, a, a]

[*a, a, *a]
[*a, 1, *a, 1]
[*a, 1, *a, *a]

[*a, a, *a, a]
```

This is because previously Ruby would use newarray and concatarray
to create the array, which both each allocate an array internally.

This changes the compilation to use concattoarray and pushtoarray,
which do not allocate arrays.  It also updates the peephole optimizer
to optimize the duparray/concattoarray sequence to
putobject/concattoarray, mirroring the existing duparray/concatarray
optimization.

These changes reduce the array allocations for the above examples to
a single array allocation, except for:

```
[*a, 1, a]
[*a, a, a]
```

The reason for this is because optimizing this case to only allocate
1 array requires changes to compile_array, which would currently
conflict with an unmerged pull request (ruby#9721).  After that pull
request is merged, it should be possible to refactor things to only
allocate a 1 array for all literal arrays (or 2 for arrays with
keyword splats).
@jeremyevans jeremyevans requested a review from jhawthorn January 26, 2024 22:23
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

Successfully merging this pull request may close these issues.

2 participants