From 251b5be20d5b58c27490f44cdeb6e655f9be6f19 Mon Sep 17 00:00:00 2001 From: Janko Marohnić Date: Sat, 4 Aug 2018 09:50:42 +0200 Subject: Reduce memory allocation when writing to SSLSocket At the moment OpenSSL::Buffering#do_write allocates some additional strings, and in my profiling writing 5MB of data allocates additional 7.7MB of strings. This patch greatly reduces memory allocations, and now writing 5MB of data allocates only additional 0.2MB of strings. This means that large file uploads would effectively not allocate additional memory anymore. Reference: https://bugs.ruby-lang.org/issues/14426 Reference: https://github.com/ruby/ruby/pull/1924 --- lib/openssl/buffering.rb | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) (limited to 'lib') diff --git a/lib/openssl/buffering.rb b/lib/openssl/buffering.rb index 1f2b2a7e..5d1586e5 100644 --- a/lib/openssl/buffering.rb +++ b/lib/openssl/buffering.rb @@ -316,20 +316,15 @@ module OpenSSL::Buffering @wbuffer << s @wbuffer.force_encoding(Encoding::BINARY) @sync ||= false - if @sync or @wbuffer.size > BLOCK_SIZE or idx = @wbuffer.rindex("\n") - remain = idx ? idx + 1 : @wbuffer.size - nwritten = 0 - while remain > 0 - str = @wbuffer[nwritten,remain] + if @sync or @wbuffer.size > BLOCK_SIZE + until @wbuffer.empty? begin - nwrote = syswrite(str) + nwrote = syswrite(@wbuffer) rescue Errno::EAGAIN retry end - remain -= nwrote - nwritten += nwrote + @wbuffer[0, nwrote] = "" end - @wbuffer[0,nwritten] = "" end end -- cgit v1.2.3