From a21199a6e0448b9783edac40cedebfd63da78df7 Mon Sep 17 00:00:00 2001 From: raul Date: Tue, 14 May 2024 15:31:55 +0200 Subject: [PATCH] Optimize client RAM memory usage The receiveMessage() function would regularly keep casting strings based on a 2048 byte array, this didn't seemingly pose a problem until I noticed the RAM usage go through the roof when the client had to be populated with the chat history of a lengthy chat log by the server. To fix this I am now creating a second array using the number of bytes being returned by the Read() method and copying the 2048 byte array's contents into it, setting the former array to nil afterwards. --- cmd/clientFunc.go | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/cmd/clientFunc.go b/cmd/clientFunc.go index e74ecf3..abdc46f 100644 --- a/cmd/clientFunc.go +++ b/cmd/clientFunc.go @@ -72,12 +72,12 @@ func Client() { defer conn.Close() data.Server = conn - nameRequest, err := receiveMessage(conn) + nameRequest, b, err := receiveMessage(conn) if err != nil { log.Fatalf("Error occurred reading from server while requesting name: %v\n", err) } fmt.Print(nameRequest) - test := make([]byte, 2048) + test := make([]byte, b) copy(test, "Password: ") if nameRequest == string(test) { @@ -87,7 +87,7 @@ func Client() { } conn.Write([]byte(pass)) - nameRequest, err := receiveMessage(conn) + nameRequest, _, err := receiveMessage(conn) if err != nil { if err != io.EOF { log.Fatalf("Error occurred reading from server while requesting name: %v\n", err) @@ -113,7 +113,7 @@ func listenMessages(g *gocui.Gui) { log.Panicln(err) } for { - messageFromServer, err := receiveMessage(data.Server) + messageFromServer, _, err := receiveMessage(data.Server) if err != nil { // What the hell is this if err == gocui.ErrQuit { @@ -130,13 +130,20 @@ func listenMessages(g *gocui.Gui) { } } -func receiveMessage(conn net.Conn) (s string, err error) { +func receiveMessage(conn net.Conn) (s string, b int, err error) { serverMessage := make([]byte, 2048) - if _, err := conn.Read(serverMessage); err != nil { - return "", err + n, err := conn.Read(serverMessage) + if err != nil { + return "", 0, err } - finalMessage := string(serverMessage) - return finalMessage, nil + + serverMessageReduced := make([]byte, n) + copy(serverMessageReduced, serverMessage) + + finalMessage := string(serverMessageReduced) + serverMessage = nil + + return finalMessage, n, nil } func scanLine() (line string, err error) {