Issue #905 has been updated by headius (Charles Nutter).


Trying to wake this beast up...

mame: I don't think we can say it would not help MRI without testing an implementation, can we? I misunderstood realloc in my comment from two years (!!!) ago According to realloc docs:

     The realloc() function tries to change the size of the allocation pointed to by ptr to size, and returns ptr.  If there is not enough room to enlarge the memory allocation pointed
     to by ptr, realloc() creates a new allocation, copies as much of the old data pointed to by ptr as will fit to the new allocation, frees the old allocation, and returns a pointer to
     the allocated memory.

This seems to indicate that except under rare circumstances where the memory after the pointer is known to be free, realloc will behave exactly like the JVM, creating a new pointer, copying data, and freeing the old pointer.

To me, this means that a pre-allocated String construction method is most definitely useful.

It also occurred to me recently that String.new does not accept an integer argument. Perhaps all we need to do is add a String.new form that takes Integer, and possibly an optional fill byte/codepoint/single-char string?
----------------------------------------
Feature #905: Add String.new(fixnum) to preallocate large buffer
https://bugs.ruby-lang.org/issues/905#change-29510

Author: headius (Charles Nutter)
Status: Feedback
Priority: Normal
Assignee: matz (Yukihiro Matsumoto)
Category: 
Target version: 2.0.0


=begin
 Because Strings are used in ruby as arbitrary byte buffers, and because the cost of growing a String increases as it gets larger (especially when it starts small), String.new should support a form that takes a fixnum and ensures the backing store will have at least that much room. This is analogous to Array.new(fixnum) which does the same thing.
 
 The simple implementation of this would just add a Fixnum check to the String.new method, and the result would be an empty string with that size buffer. This would allow heavy string-appending algorithms and libraries (like ERb) to avoid doing so many memory copies while they run.
=end



-- 
http://bugs.ruby-lang.org/