【发布时间】:2020-01-12 05:56:44
【问题描述】:
我的目标是获取一个包含可能多达一百万个条目的map[string]int,并将其分块为最大 500 的大小,并将地图发布到外部服务。我是 golang 的新手,所以我现在正在 Go Playground 中修修补补。
任何关于如何提高我的代码库效率的技巧,请分享!
游乐场:https://play.golang.org/p/eJ4_Pd9X91c
我看到的 CLI 输出是:
original size 60
chunk bookends 0 20
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
chunk bookends 20 40
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
chunk bookends 40 60
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
这里的问题是,当块书挡被正确计算时,x 的值每次都从 0 开始。我想我应该期望它从块书挡最小值开始,即 0、20、40 等。范围为什么每次都从零开始?
来源:
package main
import (
"fmt"
"math/rand"
"strconv"
)
func main() {
items := make(map[string]int)
// Generate some fake data for our testing, in reality this could be 1m entries
for i := 0; i < 60; i ++ {
// int as strings are intentional here
items[strconv.FormatInt(int64(rand.Int()), 10)] = rand.Int()
}
// Create a map of just keys so we can easily chunk based on the numeric keys
i := 0
keys := make([]string, len(items))
for k := range items {
keys[i] = k
i++
}
fmt.Println("original size", len(keys))
//batchContents := make(map[string]int)
// Iterate numbers in the size batch we're looking for
chunkSize := 20
for chunkStart := 0; chunkStart < len(keys); chunkStart += chunkSize {
chunkEnd := chunkStart + chunkSize
if chunkEnd > len(items) {
chunkEnd = len(items)
}
// Iterate over the keys
fmt.Println("chunk bookends", chunkStart, chunkEnd)
for x := range keys[chunkStart:chunkEnd] {
fmt.Print(x, ",")
// Build the batch contents with the contents needed from items
// @todo is there a more efficient approach?
//batchContents[keys[i]] = items[keys[i]]
}
fmt.Println()
// @todo POST final batch contents
//fmt.Println(batchContents)
}
}
【问题讨论】:
标签: dictionary go slice