ruby-changes:48472
From: normal <ko1@a...>
Date: Tue, 31 Oct 2017 10:37:43 +0900 (JST)
Subject: [ruby-changes:48472] normal:r60586 (trunk): webrick/httpresponse: minor cleanups to reduce memory use
normal 2017-10-31 10:37:37 +0900 (Tue, 31 Oct 2017) New Revision: 60586 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=60586 Log: 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 Modified files: trunk/lib/webrick/httpresponse.rb Index: lib/webrick/httpresponse.rb =================================================================== --- lib/webrick/httpresponse.rb (revision 60585) +++ lib/webrick/httpresponse.rb (revision 60586) @@ -396,19 +396,18 @@ module WEBrick https://github.com/ruby/ruby/blob/trunk/lib/webrick/httpresponse.rb#L396 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 https://github.com/ruby/ruby/blob/trunk/lib/webrick/httpresponse.rb#L426 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 -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/