Skip to content

Commit

Permalink
Merge pull request #964 from casperisfine/ruby-connection-shared-strings
Browse files Browse the repository at this point in the history
Optimize SocketMixin#write to avoid string copying
  • Loading branch information
byroot authored Nov 20, 2020
2 parents 02b6ce5 + 24afd8a commit f7d354f
Showing 1 changed file with 9 additions and 21 deletions.
30 changes: 9 additions & 21 deletions lib/redis/connection/ruby.rb
Original file line number Diff line number Diff line change
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,28 +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
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)
buffer = buffer.byteslice(bytes_written..-1)
end
end
end
end
Expand Down

0 comments on commit f7d354f

Please sign in to comment.