From 3b92c6315888d5d5b8026b46765cc5e2db752761 Mon Sep 17 00:00:00 2001 From: normal Date: Tue, 31 Oct 2017 01:37:37 +0000 Subject: webrick/httpresponse: minor cleanups to reduce memory use I never knew "format" was a global method alias for "sprintf"; so it was confusing to me. Normally, one would use "sprintf" since it's also available in many other languages, but Integer#to_s avoids parsing a format string so it's less bug-prone. Furthermore, favor string interpolation over String#<< since it is easier for the VM to optimize memory allocation (as in r60320). Interpolation also reduces method calls and memory overhead for inline method cache. Finally, ensure we clear all short-lived buffers for body responses. A similar change was made and measured for Net::* in r58840 showing a large memory reduction on some workloads. * webrick/httpresponse.rb (send_body_io): favor String#to_s, reduce method calls for String#<<, clear `buf' when done, avoid extra String#bytesize calls * (send_body_string): ditto git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@60586 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- lib/webrick/httpresponse.rb | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) (limited to 'lib/webrick/httpresponse.rb') diff --git a/lib/webrick/httpresponse.rb b/lib/webrick/httpresponse.rb index 2da1625fba..d76310f935 100644 --- a/lib/webrick/httpresponse.rb +++ b/lib/webrick/httpresponse.rb @@ -396,19 +396,18 @@ module WEBrick if @request_method == "HEAD" # do nothing elsif chunked? + buf = '' begin - buf = '' - data = '' - while true - @body.readpartial( @buffer_size, buf ) # there is no need to clear buf? - data << format("%x", buf.bytesize) << CRLF - data << buf << CRLF - _write_data(socket, data) - data.clear - @sent_size += buf.bytesize - end - rescue EOFError # do nothing - end + @body.readpartial(@buffer_size, buf) + size = buf.bytesize + data = "#{size.to_s(16)}#{CRLF}#{buf}#{CRLF}" + _write_data(socket, data) + data.clear + @sent_size += size + rescue EOFError + break + end while true + buf.clear _write_data(socket, "0#{CRLF}#{CRLF}") else size = @header['content-length'].to_i @@ -427,11 +426,11 @@ module WEBrick body ? @body.bytesize : 0 while buf = @body[@sent_size, @buffer_size] break if buf.empty? - data = "" - data << format("%x", buf.bytesize) << CRLF - data << buf << CRLF + size = buf.bytesize + data = "#{size.to_s(16)}#{CRLF}#{buf}#{CRLF}" + buf.clear _write_data(socket, data) - @sent_size += buf.bytesize + @sent_size += size end _write_data(socket, "0#{CRLF}#{CRLF}") else -- cgit v1.2.1