* [PATCH] string.c: ensure String#freeze resizes internal buffer
@ 2015-07-04 5:25 Eric Wong
0 siblings, 0 replies; only message in thread
From: Eric Wong @ 2015-07-04 5:25 UTC (permalink / raw)
To: spew
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
---
string.c | 2 +-
test/ruby/test_optimization.rb | 19 +++++++++++++++++++
2 files changed, 20 insertions(+), 1 deletion(-)
diff --git a/string.c b/string.c
index 34c77a5..15d4220 100644
--- a/string.c
+++ b/string.c
@@ -9143,7 +9143,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 4a5484e..e2efc9d 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)
--
EW
^ permalink raw reply related [flat|nested] only message in thread
only message in thread, other threads:[~2015-07-04 5:25 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2015-07-04 5:25 [PATCH] string.c: ensure String#freeze resizes internal buffer Eric Wong
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).