From 9c295cab3e9c9326a4eebcd762d418fae237e25b Mon Sep 17 00:00:00 2001
From: Eric Wong <e@80x24.org>
Date: Thu, 25 Sep 2014 10:42:16 +0000
Subject: [PATCH] io.c (fptr_finalize): free memory before GC sweep

This releases memory on explict calls to rb_io_close,
reducing pressure on the GC.

Final massif snapshot shows reduced heap usage after RubyGems load
(valgrind --tool=massif ./ruby -e exit)

before:
	mem_heap_B=4821992
	mem_heap_extra_B=1302952

after:
	mem_heap_B=4791056
	mem_heap_extra_B=1192440
---
 io.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/io.c b/io.c
index 876ae67..f4b41dd 100644
--- a/io.c
+++ b/io.c
@@ -4251,6 +4251,9 @@ maygvl_fclose(FILE *file, int keepgvl)
     return (int)(intptr_t)rb_thread_call_without_gvl(nogvl_fclose, file, RUBY_UBF_IO, 0);
 }
 
+static void free_io_buffer(rb_io_buffer_t *buf);
+static void clear_codeconv(rb_io_t *fptr);
+
 static void
 fptr_finalize(rb_io_t *fptr, int noraise)
 {
@@ -4312,6 +4315,9 @@ fptr_finalize(rb_io_t *fptr, int noraise)
             rb_exc_raise(err);
         }
     }
+    free_io_buffer(&fptr->rbuf);
+    free_io_buffer(&fptr->wbuf);
+    clear_codeconv(fptr);
 }
 
 static void
-- 
EW

