Skip to content

Commit

Permalink
Optimize SocketMixin#write to avoid string copying
Browse files Browse the repository at this point in the history
  • Loading branch information
byroot committed Nov 19, 2020
1 parent 02b6ce5 commit a910870
Showing 1 changed file with 7 additions and 21 deletions.
28 changes: 7 additions & 21 deletions lib/redis/connection/ruby.rb
Expand Up @@ -67,10 +67,13 @@ def _read_from_socket(nbytes)
end
end

def _write_to_socket(data)
def write(buffer)
return super(buffer) unless @write_timeout

bytes_to_write = buffer.bytesize
total_bytes_written = 0
loop do
case bytes_written = write_nonblock(data, exception: false)
case bytes_written = write_nonblock(buffer, exception: false)
when :wait_readable
unless wait_readable(@write_timeout)
raise Redis::TimeoutError
Expand All @@ -83,30 +86,13 @@ def _write_to_socket(data)
raise Errno::ECONNRESET
when Integer
total_bytes_written += bytes_written
if bytes_written < data.bytesize
data.slice!(0, bytes_written)
else
if total_bytes_written >= bytes_to_write
return total_bytes_written
end
buffer = buffer.byteslice(bytes_written..-1)
end
end
end

def write(data)
return super(data) unless @write_timeout

data = data.b
length = data.bytesize
total_count = 0
loop do
count = _write_to_socket(data)

total_count += count
return total_count if total_count >= length

data = data.byteslice(count..-1)
end
end
end

if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
Expand Down

0 comments on commit a910870

Please sign in to comment.