Project

General

Profile

Actions

Feature #17790

open

Have a way to clear a String without resetting its capacity

Added by byroot (Jean Boussier) about 1 year ago. Updated about 1 year ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:103342]

Description

In some tight loop it can be useful to re-use a buffer string. For instance:

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:

>> 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?

Actions

Also available in: Atom PDF