Project

General

Profile

Actions

Feature #18683

closed

Allow to create hashes with a specific capacity.

Added by byroot (Jean Boussier) over 2 years ago. Updated about 2 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:108185]

Description

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.

Example of code that would benefit:

String and Array both already offer similar APIs:

String.new(capacity: XXX)
Array.new(XX) / rb_ary_new_capa(long)

However there's no such public API for Hashes, neither in Ruby land not in the C extension API.

Proposal

I think Hash.new should accept a capacity: named parameter:

hash = Hash.new(capacity: 1000)

Additionally I think the internal rb_hash_new_with_size function should be exposed to C extensions as rb_hash_new_capa(long), for consistency with rb_ary_new_capa(long).


Related issues 1 (0 open1 closed)

Related to Ruby master - Feature #19236: Allow to create hashes with a specific capacity from RubyClosedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0