登录
首页 >  Golang >  Go问答

在Golang中利用唯一数组值进行并发映射操作

来源:stackoverflow

时间:2024-03-18 22:09:34 103浏览 收藏

在 Go 语言中,使用并发映射可以高效地存储和检索数据。然而,当需要向映射中添加唯一值时,使用线性扫描检查重复项的方法会变得低效,尤其是当数据集庞大时。为了提高效率,可以使用其他数据结构,例如嵌套映射,来避免线性扫描。通过使用空结构作为映射中的值,可以优化内存使用并提高查找性能。

问题内容

我正在迭代 flatproduct.catalogs 切片并在 golang 中填充我的 productcatalog 并发映射。我正在使用 upsert 方法,以便只能将唯一的 productid 的 添加到我的 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 {
  ...
}

正确答案


总结评论中的答案:

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
})

嵌套映射会添加大量分配,导致大量内存使用,对吗?

不,使用空结构不会创建新的分配或增加内存使用量。您可以找到大量有关空结构及其用法的文章/问题。 (例如What uses a type with empty struct has in Go?

注意:您可以对数组使用某种优化搜索,例如 sort.Search 使用的二分搜索,但它需要排序数组

今天关于《在Golang中利用唯一数组值进行并发映射操作》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>