From 7dd51deb4888c646c57e12088043a271049b2302 Mon Sep 17 00:00:00 2001 From: Thiago Kenji Okada Date: Thu, 25 Jul 2024 11:08:25 +0100 Subject: [PATCH] request: use bufio.Reader and bufio.Writer Before: ``` goos: linux goarch: amd64 pkg: github.com/thiagokokada/hyprland-go cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkSplash BenchmarkSplash-16 35851 34729 ns/op PASS ok github.com/thiagokokada/hyprland-go 1.595s`` ``` Bufio.Reader: ``` goos: linux goarch: amd64 pkg: github.com/thiagokokada/hyprland-go cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkSplash BenchmarkSplash-16 30976 38695 ns/op PASS ok github.com/thiagokokada/hyprland-go 1.604s ``` Bufio.Reader + Bufio.Writer: ``` goos: linux goarch: amd64 pkg: github.com/thiagokokada/hyprland-go cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkSplash BenchmarkSplash-16 29901 40494 ns/op PASS ok github.com/thiagokokada/hyprland-go 1.630s ``` --- request.go | 9 +++++++-- request_test.go | 9 +++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/request.go b/request.go index 2d83aa3..7e7732d 100644 --- a/request.go +++ b/request.go @@ -1,6 +1,7 @@ package hyprland import ( + "bufio" "bytes" "encoding/json" "errors" @@ -240,16 +241,20 @@ func (c *RequestClient) RawRequest(request RawRequest) (response RawResponse, er request, ) } - _, err = conn.Write(request) + + writer := bufio.NewWriter(conn) + _, err = writer.Write(request) if err != nil { return nil, fmt.Errorf("error while writing to socket: %w", err) } + writer.Flush() // Get the response back rbuf := bytes.NewBuffer(nil) sbuf := make([]byte, BUF_SIZE) + reader := bufio.NewReader(conn) for { - n, err := conn.Read(sbuf) + n, err := reader.Read(sbuf) if err != nil { if err == io.EOF { break diff --git a/request_test.go b/request_test.go index 2be0fd2..8cc4bd5 100644 --- a/request_test.go +++ b/request_test.go @@ -325,6 +325,15 @@ func TestSplash(t *testing.T) { testCommand(t, c.Splash, "") } +func BenchmarkSplash(b *testing.B) { + if c == nil { + b.Skip("HYPRLAND_INSTANCE_SIGNATURE not set, skipping test") + } + for i := 0; i < b.N; i++ { + c.Splash() + } +} + func TestWorkspaces(t *testing.T) { testCommand(t, c.Workspaces, []Workspace{}) }