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.
This commit is contained in:
raul 2024-05-14 15:31:55 +02:00
parent 5bb37a53fe
commit a21199a6e0
1 changed files with 16 additions and 9 deletions

View File

@ -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) {