From: "Dan0042 (Daniel DeLorme) via ruby-core" Date: 2023-05-05T23:59:37+00:00 Subject: [ruby-core:113408] [Ruby master Feature#19236] Allow to create hashes with a specific capacity from Ruby Issue #19236 has been updated by Dan0042 (Daniel DeLorme). Previousy, a `capacity` reader/writer was suggested by @byroot in #18683#note-2 I would like to see this idea considered more seriously because 1. It doesn't need to change anything to the initialize arguments of Array/Hash/String, which are already quite complex enough 2. The same API can be used for any class; it's nicely consistent and easy to remember 3. It's more versatile, as it can be used more than once after object creation, ex: ```ruby buffer = String.new #this example is with String, but the same could apply to Hash/Array while line = gets #increase buffer capacity by chunks of 10k buffer.capacity += 10000 if buffer.capacity < buffer.bytesize + line.bytesize buffer << line end buffer.capacity = 0 #trim buffer to minimal size (aka "right-size") buffer.capacity == buffer.bytesize #=> true ``` ---------------------------------------- Feature #19236: Allow to create hashes with a specific capacity from Ruby https://bugs.ruby-lang.org/issues/19236#change-102979 * Author: byroot (Jean Boussier) * Status: Open * Priority: Normal * Target version: 3.3 ---------------------------------------- Followup on [Feature #18683] which added a C-API for this purpose. Various protocol parsers such as Redis `RESP3` or `msgpack`, have to create hashes, and they know the size in advance. For efficiency, it would be preferable if they could directly allocate a Hash of the necessary size, so that large hashes wouldn't cause many re-alloccations and re-hash. `String` and `Array` both already offer similar APIs: ```ruby String.new(capacity: XXX) Array.new(XX) / rb_ary_new_capa(long) ``` However there's no such public API for Hashes in Ruby land. ### Proposal I think `Hash` should have a way to create a new hash with a `capacity` parameter. The logical signature of `Hash.new(capacity: 1000)` was deemed too incompatible in [Feature #18683]. @Eregon proposed to add `Hash.create(capacity: 1000)`. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/