我正在遍歷flatProduct.Catalogs切片并在 golang 中填充我的productCatalog 并發地圖。我正在使用 upsert 方法,以便我只能將唯一的添加productID's到我的productCatalog地圖中。
這使用線性掃描來檢查重復的產品 ID,但在我的情況下,我有超過 700k 的產品 ID,所以它對我來說非常慢。我正在尋找提高效率的方法。
下面的代碼由多個 goroutine 并行呼叫,這就是為什么我在這里使用并發映射將資料填充到其中的原因。
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 代碼對我來說非常慢,在我的并發地圖中添加唯一的產品 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 {
...
}
uj5u.com熱心網友回復:
總結評論的答案:
upsert 函式是 O(n**2),其中 n 是切片的長度。
您還提到的問題是遍歷整個切片以查找重復項。使用另一張地圖可以避免這種情況。
示例:
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
})
嵌套地圖會增加大量分配,導致大量記憶體使用,對嗎?
不,使用空結構不會創建新的分配或增加記憶體使用量。您可以找到大量關于空結構及其用法的文章/問題。(例如,Go 中有什么使用空結構的型別?)
注意:您可以對陣列使用某種優化搜索,例如sort.Search使用的二進制搜索,但它需要 sorted array。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448505.html
