The use of unsafe improve performance

Go this way is recommended, the advantage is safety, although the memory copy operation will occur, resulting in loss will be on performance, general business in dealing with this loss is negligible. However, if the copy is frequently the case, when you want to optimize the performance, the need to introduce unsafe.Pointer:

func main()  {
    var s = []byte("我永远喜欢藤原千花.jpg")
    Res := *(*string)(unsafe.Pointer(&s))
    fmt.Println(Res)
}

String forged by unsafe.Pointer memory copy process not occur, so the efficiency will be faster than the memory copy of the type of conversion occurs, but at the expense expose the underlying data, that is unsafe practice.

As for why Slice through this way and String conversion, we can look at their underlying structure SliceHeader and StringHeader:

type SliceHeader struct {
    Data uintptr
    Len  int
    Cap  int
  }
type StringHeader struct {
    Data uintptr
    Len  int
  }
两种类型只差了一个字段Cap(容量),前面剩余的字段都是内存对齐的,所以可以直接转换




Guess you like

Origin www.cnblogs.com/hualou/p/12069768.html