From: dylan.smith@... Date: 2021-04-09T18:44:39+00:00 Subject: [ruby-core:103353] [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). If we want `clear` to shrink memory by default, a `shrink: true` keyword argument could be added so the user could override this default with `clear(shrink: false)`. This would make the change less risky, since it wouldn't change the behaviour of existing code. ---------------------------------------- Feature #17790: Have a way to clear a String without resetting its capacity https://bugs.ruby-lang.org/issues/17790#change-91444 * 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: