Skip to content

Patch allocate instead of .new#22

Closed
amomchilov wants to merge 1 commit intoAlex/abstract-classesfrom
Alex/experiments/patch-allocate
Closed

Patch allocate instead of .new#22
amomchilov wants to merge 1 commit intoAlex/abstract-classesfrom
Alex/experiments/patch-allocate

Conversation

@amomchilov
Copy link
Contributor

@amomchilov amomchilov commented Mar 5, 2026

Failed experiment.

Hypotheseses:

  1. Hiding a slow path in allocate is preferable to putting it in new, because allocate is much more rarely overridden.
  2. Patching allocate would be more performant than new, because it's 0 arity and you don't need to pay any overhead to forward arguments.

Doesn't work at all, because an overridden allocate is not called by new.

class Foo
  class << self
    def allocate
      raise "This never gets called"
    end
  end
  
  def initialize
    puts "init"
    super()
  end
end

Foo.new # => only calls init

I thought the the default implementation Class#new would work something like:

class Class
  def new(...) = allocate.send(:initialize, ...)
end

Which is close, except the implementation in C makes a direct call to allocate, without dynamic dispatch: https://github.com/ruby/ruby/blob/a8cb7292c6790d12a72000c1e19e62f05ea63f6a/object.c#L2370

This was referenced Mar 5, 2026
@amomchilov
Copy link
Contributor Author

amomchilov commented Mar 5, 2026

Warning

This pull request is not mergeable via GitHub because a downstack PR is open. Once all requirements are satisfied, merge this PR as a stack on Graphite.
Learn more

This stack of pull requests is managed by Graphite. Learn more about stacking.

@amomchilov amomchilov mentioned this pull request Mar 5, 2026
@amomchilov amomchilov closed this Mar 9, 2026
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.

1 participant