From: dylan.smith@... Date: 2021-04-09T18:39:00+00:00 Subject: [ruby-core:103352] [Ruby master Feature#17790] Have a way to clear a String without resetting its capacity Issue #17790 has been updated by dylants (Dylan Thacker-Smith). What makes sense probably depends on how long lived the String is and whether there is an upper-bound to how much needs to be stored in it. For instance, there may be a rare iteration of a loop that adds a lot to the String, which might be excessive to hold onto for most iterations. As such, we may want to shrink the String back to the capacity we expect most iterations to use, such as the initial capacity. It would be nice to have more control over the capacity of collections, such as Array or String. If we know exactly how much memory is needed, then it would be useful to have `shrink(capacity = bytesize)` and `reserve(capacity)` for this purpose. It is also common to not know at least a specific amount of memory needs to be reserved, but to not know exactly how much is needed, so providing a `capacity` method gives more control over how to expand memory (e.g. double capacity until it is at least the minimum amount needed, then call `reserve` with that expanded capacity). This would provide the primitives needed to avoid unnecessary reallocations, which convenience methods can always be built on top of. ---------------------------------------- Feature #17790: Have a way to clear a String without resetting its capacity https://bugs.ruby-lang.org/issues/17790#change-91443 * Author: byroot (Jean Boussier) * Status: Open * Priority: Normal ---------------------------------------- In some tight loop it can be useful to re-use a buffer string. For instance: ```ruby buffer = String.new(encoding: Encoding::BINARY, capacity: 1024) 10.times do build_next_packet(buffer) udp_socket.send(buffer) buffer.clear end ``` Currently `Array#clear` preserve the Array capacity, but `String#clear` doesn't: ```ruby >> puts ObjectSpace.dump(Array.new(20).clear) {"address":"0x7fd3260a1558", "type":"ARRAY", "class":"0x7fd3230972e0", "length":0, "memsize":200, "flags":{"wb_protected":true}} >> puts ObjectSpace.dump(String.new(encoding: Encoding::BINARY, capacity: 1024).clear) {"address":"0x7fd322a8a320", "type":"STRING", "class":"0x7fd3230b75b8", "embedded":true, "bytesize":0, "value":"", "memsize":40, "flags":{"wb_protected":true}} ``` It would be useful if `String#clear` wouldn't free allocated memory, but if it's a backward compatibility concern to change it, then maybe another method could make sense? -- https://bugs.ruby-lang.org/ Unsubscribe: