From a3f68d8d1fd23e00af6b7e1ffaeb1ce1a6b252b9 Mon Sep 17 00:00:00 2001 From: hashmap Date: Fri, 18 Jan 2019 15:11:13 +0100 Subject: [PATCH] Reduce number of String allocation in Stratum worker Currently we allocate a string in the heap per each worker check (not even read) and clone message in write. This pr introduces a buffer which is used for a round of workers check and remove clone in write_message. Read optimization reduces number of allocations by factor of N (where N is a number of workers), if N = 1 number of allocations doesn't change. --- servers/src/mining/stratumserver.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/servers/src/mining/stratumserver.rs b/servers/src/mining/stratumserver.rs index 0c4791df5..5c3d37c7c 100644 --- a/servers/src/mining/stratumserver.rs +++ b/servers/src/mining/stratumserver.rs @@ -168,12 +168,11 @@ impl Worker { } // Get Message from the worker - fn read_message(&mut self) -> Option { + fn read_message(&mut self, line: &mut String) -> Option { // Read and return a single message or None - let mut line = String::new(); - match self.stream.read_line(&mut line) { - Ok(_) => { - return Some(line); + match self.stream.read_line(line) { + Ok(n) => { + return Some(n); } Err(ref e) if e.kind() == ErrorKind::WouldBlock => { // Not an error, just no messages ready @@ -191,9 +190,8 @@ impl Worker { } // Send Message to the worker - fn write_message(&mut self, message_in: String) { + fn write_message(&mut self, mut message: String) { // Write and Flush the message - let mut message = message_in.clone(); if !message.ends_with("\n") { message += "\n"; } @@ -283,9 +281,10 @@ impl StratumServer { // Handle an RPC request message from the worker(s) fn handle_rpc_requests(&mut self, stratum_stats: &mut Arc>) { let mut workers_l = self.workers.lock(); + let mut the_message = String::with_capacity(4096); for num in 0..workers_l.len() { - match workers_l[num].read_message() { - Some(the_message) => { + match workers_l[num].read_message(&mut the_message) { + Some(_) => { // Decompose the request from the JSONRpc wrapper let request: RpcRequest = match serde_json::from_str(&the_message) { Ok(request) => request,