New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
quote: Convert []byte to string using unsafe to avoid realloc #75
Conversation
@fhs I was wrong about the Unicode part in the previous PR, but after looking at the compiled binary, I saw the buffer was being reallocated into a string. This uses |
I don't like using |
When I tried it out and checked the assembly output, it looked like operations weren't inlined. I think buffer+unsafe is a cleaner approach. If you're concerned about the safety, this method to convert Good idea. I wrote a quick PR #77. I'll look into results later. |
I'm more concerned that we're assuming that memory layout of |
That's true, it should be much easier when |
Difference, without using
|
Difference, using diff --git a/mpd/client.go b/mpd/client.go
index addfcc7..5430d5c 100644
--- a/mpd/client.go
+++ b/mpd/client.go
@@ -21,19 +21,19 @@ import (
// NB: this function shouldn't be used on the PROTOCOL LEVEL because it considers single quotes special chars and
// escapes them.
func quote(s string) string {
- q := make([]byte, 2+2*len(s))
- i := 0
- q[i], i = '"', i+1
+ var q strings.Builder
+ q.Grow(2 + 2*len(s))
+ q.WriteByte('"')
for _, c := range []byte(s) {
// We need to escape single/double quotes and a backslash by prepending them with a '\'
switch c {
case '"', '\\', '\'':
- q[i], i = '\\', i+1
+ q.WriteByte('\\')
}
- q[i], i = c, i+1
+ q.WriteByte(c)
}
- q[i], i = '"', i+1
- return unsafe_String(q[:i:i])
+ q.WriteByte('"')
+ return q.String()
}
// Quote quotes each string of args in the format understood by MPD.
|
Looks like using both have equal improvements in memory usage. The The The version using |
@fhs What do you think? |
Let's use the version using |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks!
No description provided.