duanmei1536 2014-08-12 00:42
浏览 62

使用字节切片(或数组)时,优化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 2014-08-12 00:46
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题