This article is nearly devoid of any actual content.
Like most other content these days. Three statements, wrapped with tons of fluff. It’s hard to conform to the rules of the SEO machine otherwise.
Thanks for the feedback anyway ;)
From following StackOverflow’s Go tag a while, beginners do get confused about this. I think it’s not a bad rule of thumb to leave bytes as bytes until it becomes inconvenient or (due to mutability) confusing/bug-prone, not convert because a string seems inherently right for some kind of content. Some context:
Slightly different but related idea: stream when you can. If you don’t do anything tricky to save allocs, building up a big HTTP response in a string/byte likely makes more garbage than outputting little bits at a time. So Go’s html/template, for example, takes a Writer instead of returning the whole page as a string or byte slice.
Also if you start with code to do little writes then someday want a big string/byte, no problem: pass in bytes.Buffer as the writer. Harder to go the other direction.
The benefits of streaming can also apply other places of your pipeline, not just requests/response/file I/O, e.g. you can read a row from your DB, do something with it, read another row… instead of building up a big table structure in memory. If you’re lucky, you might lazily write an app that can deal with heavy requests without exploding, or at least can keep a lot of simultaneous connections in flight gracefully.
It’s about “byte slices” (byte), not “byte arrays” (byte). But to be fair, the distinction doesn’t matter much for the gist of the post.
Totally correct. I think, I even mention it somewhere in the post. The thing is, I wanted to make the post applicable to a broader audience coming to Go for the first time. Since a byte slice and a byte array are pretty much interchangeable concepts in this context, I decided to the stick to using byte array everywhere. It’s just what most programmers would know as a term.
Do byte arrays allocate in-place though? That would have a bearing on cache locality for performance or unsafe access. When glossing over details I like to at least know that it’s being done to follow up on later.
I like this. Using byte everywhere can be better for performance. In i.e Spring / Java you may not be able to get to the byte array all the time without going through a String (which can be wasteful).