diff --git a/ChangeLog b/ChangeLog index 5bcbb305da..a897ae5cc2 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +Tue Jul 7 04:42:25 2015 Eric Wong + + * 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 * vm.c (vm_define_method): remove an unused local variable. diff --git a/string.c b/string.c index 6ef92eb9fb..03922e56c1 100644 --- a/string.c +++ b/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); diff --git a/test/ruby/test_optimization.rb b/test/ruby/test_optimization.rb index 4a5484e43d..e2efc9d11c 100644 --- a/test/ruby/test_optimization.rb +++ b/test/ruby/test_optimization.rb @@ -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)