In the case of high performance IO, where probably most strings are converted, 
you use a ByteBuffer to avoid many small kernel calls anyway, and these can 
copy the string data (WriteString) to the buffer directly without an 
intermediate allocation. 

> On Jul 5, 2019, at 7:00 AM, Slawomir Pryczek <slawek1...@gmail.com> wrote:
> 
> Not sure if that's a good idea. Strings are immutable so you can pass string 
> to function by reference, in thread safe manner. So if you pass same string 
> to 2 threads and one of them modify it - you'll really have 
> allocate+copy+modify so you're never touching the original thing so you can't 
> have a race.
> 
> Now if go introduced readolny []byte, we'd probably want to change all io 
> functions to use that... and this would create a lot of confusion, because 
> it'd be required to cast []byte to readonly version. And this casted variable 
> wouldn't be readonly nor thread-safe at all, because underlying memory could 
> still be changed using the original slice. So we'd need allocate+memcopy for 
> readonly cast to do a network write.
> 
> Or maybe there could be readonly []byte version for each io op. But it'd 
> result only in many unnecessary OS calls.
> 
> So what is needed in this case (i guess) is a reusable buffer anyway, and 
> then you can do a copy to a byte buffer without a cast and allocation
> tstr := "abc"
> t := make([]byte, 10, 10)
> copy(t, tstr)
> 
> W dniu piątek, 5 lipca 2019 04:27:58 UTC+2 użytkownik Ally Dale napisał:
>> 
>> []byte is mutable in Go, but string is readonly,  so []byte(string) in Go is 
>> actually allocate&memcopy, and this operation is costly.
>> Sometimes, we need a readonly []byte parameter but we have string only, and 
>> we have no choice but allocate&memcopy to make a new []byte variable from 
>> string.
>> Eg: net.Send([]byte("ping")) is costly,  but net.Send(readonly 
>> []byte("ping"))  can be cheaply.
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/golang-nuts/804e9ecf-4d2e-4ffd-8cca-1a9c91928bb9%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/51001CD5-CB26-470F-A97D-12AFF0C4C7E1%40ix.netcom.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to