[英]Add unique values in an array as a value in concurrent map golang?
我正在迭代flatProduct.Catalogs
切片並在 golang 中填充我的productCatalog
並發map。 我正在使用 upsert 方法,以便我只能將唯一的productID's
添加到我的productCatalog
中。
這使用線性掃描來檢查重復的產品 ID,但在我的例子中,我有超過 700k 的產品 ID,所以它對我來說非常慢。 我正在尋找提高效率的方法。
下面的代碼由多個 goroutine 並行調用,這就是為什么我在這里使用並發 map 將數據填充到其中。
var productRows []ClientProduct
err = json.Unmarshal(byteSlice, &productRows)
if err != nil {
return err
}
for i := range productRows {
flatProduct, err := r.Convert(spn, productRows[i])
if err != nil {
return err
}
if flatProduct.StatusCode == definitions.DONE {
continue
}
r.products.Set(strconv.Itoa(flatProduct.ProductId, 10), flatProduct)
for _, catalogId := range flatProduct.Catalogs {
catalogValue := strconv.FormatInt(int64(catalogId), 10)
// how can I improve below Upsert code for `productCatalog` map so that it can runs faster for me?
r.productCatalog.Upsert(catalogValue, flatProduct.ProductId, func(exists bool, valueInMap interface{}, newValue interface{}) interface{} {
productID := newValue.(int64)
if valueInMap == nil {
return []int64{productID}
}
oldIDs := valueInMap.([]int64)
for _, id := range oldIDs {
if id == productID {
// Already exists, don't add duplicates.
return oldIDs
}
}
return append(oldIDs, productID)
})
}
}
上面的 upsert 代碼對我來說非常慢,並且在我的並發 map 中添加唯一產品 ID 作為值需要花費很多時間。這里是productCatalog
的定義方式。
productCatalog *cmap.ConcurrentMap
這是我正在使用的upsert
方法 - https://github.com/orcaman/concurrent-map/blob/master/concurrent_map.go#L56
這就是我從這個 cmap 讀取數據的方式:
catalogProductMap := clientRepo.GetProductCatalogMap()
productIds, ok := catalogProductMap.Get("200")
var data = productIds.([]int64)
for _, pid := range data {
...
}
upsert function 是 O(n**2) ,其中 n 是切片的長度。
您還提到的問題是遍歷整個切片以查找重復項。 使用另一個 map 可以避免這種情況。
示例:
r.productCatalog.Upsert(catalogValue, flatProduct.ProductId, func(exists bool, valueInMap interface{}, newValue interface{}) interface{} {
productID := newValue.(int64)
if valueInMap == nil {
return map[int64]struct{}{productID: {}}
}
oldIDs := valueInMap.(map[int64]struct{})
// value is irrelevant, no need to check if key exists
oldIDs[productID] = struct{}{}
return oldIDs
})
嵌套 map 會增加大量分配,導致大量 memory 的使用,對嗎?
不,使用空結構不會創建新的分配或增加 memory 的使用。 您可以找到很多關於空結構及其用法的文章/問題。 (例如,在 Go 中,什么使用了具有空結構的類型? )
注意:您可以對數組使用某種優化搜索,例如sort.Search使用的二進制搜索,但它需要排序數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.