mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
string.c: ensure String#freeze resizes internal buffer
rb_str_freeze may resize oversized buffers to save memory, so favor it over rb_obj_freeze. This is useful because IO methods do not prematurely shrink buffers, as they are likely to be overwritten with full data. * string.c (Init_String): use rb_str_freeze for String#freeze git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@51170 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
parent
57f2c60727
commit
bbf7495fe2
3 changed files with 26 additions and 1 deletions
|
@ -1,3 +1,9 @@
|
|||
Tue Jul 7 04:42:25 2015 Eric Wong <e@80x24.org>
|
||||
|
||||
* string.c (Init_String): use rb_str_freeze for String#freeze
|
||||
to resize internal buffer
|
||||
[ruby-core:69870] [Feature #11330]
|
||||
|
||||
Tue Jul 7 04:12:32 2015 Koichi Sasada <ko1@atdot.net>
|
||||
|
||||
* vm.c (vm_define_method): remove an unused local variable.
|
||||
|
|
2
string.c
2
string.c
|
@ -9150,7 +9150,7 @@ Init_String(void)
|
|||
rb_define_method(rb_cString, "byteslice", rb_str_byteslice, -1);
|
||||
rb_define_method(rb_cString, "scrub", str_scrub, -1);
|
||||
rb_define_method(rb_cString, "scrub!", str_scrub_bang, -1);
|
||||
rb_define_method(rb_cString, "freeze", rb_obj_freeze, 0);
|
||||
rb_define_method(rb_cString, "freeze", rb_str_freeze, 0);
|
||||
|
||||
rb_define_method(rb_cString, "to_i", rb_str_to_i, -1);
|
||||
rb_define_method(rb_cString, "to_f", rb_str_to_f, 0);
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
require 'test/unit'
|
||||
require 'objspace'
|
||||
|
||||
class TestRubyOptimization < Test::Unit::TestCase
|
||||
|
||||
|
@ -122,6 +123,24 @@ class TestRubyOptimization < Test::Unit::TestCase
|
|||
assert_redefine_method('String', 'freeze', 'assert_nil "foo".freeze')
|
||||
end
|
||||
|
||||
def test_string_freeze_saves_memory
|
||||
n = 16384
|
||||
data = '.'.freeze
|
||||
r, w = IO.pipe
|
||||
w.write data
|
||||
|
||||
s = r.readpartial(n, '')
|
||||
assert_operator ObjectSpace.memsize_of(s), :>=, n,
|
||||
'IO buffer NOT resized prematurely because will likely be reused'
|
||||
|
||||
s.freeze
|
||||
assert_equal ObjectSpace.memsize_of(data), ObjectSpace.memsize_of(s),
|
||||
'buffer resized on freeze since it cannot be written to again'
|
||||
ensure
|
||||
r.close if r
|
||||
w.close if w
|
||||
end
|
||||
|
||||
def test_string_eq_neq
|
||||
%w(== !=).each do |m|
|
||||
assert_redefine_method('String', m, <<-end)
|
||||
|
|
Loading…
Reference in a new issue