duanmei1536
duanmei1536
2014-08-12 00:42

使用字节切片(或数组)时,优化go(golang)代码有哪些技巧? [关闭]

I waw wondering what could be some of the common pitfalls that a novice go programmer could fall in when writing (unintentionally slow go code).

1) First, I know that in python doing string concatenation can be (or used to be expensive), is that the same in go when trying to add one element to a string? As in "hello"+"World".

2) The other issue is that I find myself very often having to extend my slice with a list of more bytes (rather than 1 byte at a time). I have a "dirty" way of appending it by doing the following:

newStr := string(arrayOfBytes) + string(newBytesToAppend)

Is that way slower than just doing something like?

for _, b := range newBytesToAppend{
    arrayOfBytes = append(arrayOfBytes, b)
}

Or is there a better way to append whole slices to other slices or maybe a built in way? It just seems to me a little odd that I would even have to write my own extend function (or even benchmark it)

Also, sometimes I end up having to loop through every element of the byte slice and for readability, I change the type of that current byte to a string. As in:

for _, b := range newBytesToAppend{
    c := string(b)
    //some more logic on c
    logic(c) //logic
}

3) I was wondering, if converting types in go is expensive (specially between string to arrays) and if that might be one of the factors that might be making the code slow. Btw, sometimes I change types (to strings) very often, nearly every iteration.

But more generally, I was trying to search for the web a list of hints of what often are things that makes go code slow and was trying to change it so that it wouldn't (but didn't have that much luck). I am very much aware that this depends from application to application, but was wondering if there are any "expert" advice on what usually makes "novice" go code slow.

4) The last thing I can think of is, that sometimes I do know in advance the length of the slice, so I could just use arrays with fixed length. Could that change anything?

5) I have also made my own types as in:

type Num int

or

type Name string

Do those hinder performance?

6) Is there a general list of heuristic to watch out in go for code optimization? For example, is dereferencing a problem as it can be in C?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duannaozhao4626 duannaozhao4626 7年前

    Use bytes.Buffer / Buffer.Write, it handles re-sizing the internal slice for you and it's by far the most effiecent way to manage multiple []bytes.

    About the 2nd question, it's rather easy to answer that using a simple benchmark.

    点赞 评论 复制链接分享