Project

General

Profile

Actions

Feature #21274

open

Show performance warnings for easily avoidable unnecessary implicit splat allocations

Added by jeremyevans0 (Jeremy Evans) about 21 hours ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:121686]

Description

In Ruby 3.4, I made many changes to reduce implicit allocations (mostly in method calling). There are still a few cases where Ruby must allocate an array for a positional splat, or a hash for a keyword splat. Some of these allocations are unavoidable, but in other cases, while Ruby cannot avoid the allocation, it is easy for a user to make a small change to their code to avoid the allocation. One example of this is when Ruby allocates to avoid an evaluation order issue. For example:

def kw = nil
ary = []
m(*ary, kw:)

Ruby allocates an array for *ary, even though it does not need to, because kw is a method call, and the method call could potentially modify ary (it doesn't in this example, but Ruby's compiler cannot assume that, as the method may be overridden later). It is simple to avoid the allocation by using a local variable:

def kw = nil
ary = []
kw = self.kw
m(*ary, kw:)

To make it easier for users to find and avoid these unnecessary implicit allocations, I would like to add a performance warning in cases where Ruby allocates solely to avoid an evaluation order issue.

I've submitted a pull request to implement this: https://github.com/ruby/ruby/pull/13135

The current warning messages in the pull request are quite verbose:

$ ruby -W:performance -e 'def kw; {} end; a = []; p(*a, **kw)'
-e: warning: This method call implicitly allocates a potentially unnecessary
array for the positional splat, because a keyword, keyword splat, or block pass
expression could cause an evaluation order issue if an array is not allocated
for the positional splat. You can avoid this allocation by assigning the related
keyword, keyword splat, or block pass expression to a local variable and using
that local variable.

$ ruby -W:performance -e 'def b; ->{} end; h = {}; p(**h, &b)'
-e: warning: This method call implicitly allocates a potentially unnecessary
hash for the keyword splat, because the block pass expression could cause an
evaluation order issue if a hash is not allocated for the keyword splat. You
can avoid this allocation by assigning the block pass expression to a local
variable, and using that local variable.

It may be desirable to shorten these messages, so I would appreciate suggestions.

No data to display

Actions

Also available in: Atom PDF

Like0