1

在已知長度情況下優化 slice 的性能

 2 years ago
source link: https://blog.niclin.tw/2019/12/29/length-slice-init-golang/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Nic Lin's Blog

喜歡在地上滾的工程師

golang 在用 slice 時要注意,如果先給大小的話可以避免動態的多次 allocate 多的 memory,然後讓底層產生多個 slice

假設從 SQL 拿出來的資料已經知道其長度,再塞資料到 slice 時如果用空的類似 []SomeRecord 效能上反而比較不好。

提升效能的作法應該是直接指定 slice 長度,例如

make([]SomeRecord, 0, len(sqlResults))

從參考文章的 benchmark 來看,空的 init 是最慢的,其餘不管是 append or direct access 的作法差異就不這麼大了


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK