data-structures - Golang 中的 map 访问瓶颈

标签 data-structures go hashmap

我正在使用 Golang 为具有超过 30000 个可能标签的数据集实现朴素贝叶斯分类。我已经建立了模型,并且处于分类阶段。我正在对 1000 条记录进行分类,这最多需要 5 分钟。我已经使用 pprof 功能分析了代码;前 10 名如下所示:

Total: 28896 samples
   16408  56.8%  56.8%    24129  83.5% runtime.mapaccess1_faststr
    4977  17.2%  74.0%     4977  17.2% runtime.aeshashbody
    2552   8.8%  82.8%     2552   8.8% runtime.memeqbody
    1468   5.1%  87.9%    28112  97.3% main.(*Classifier).calcProbs
     861   3.0%  90.9%      861   3.0% math.Log
     435   1.5%  92.4%      435   1.5% runtime.markspan
     267   0.9%  93.3%      302   1.0% MHeap_AllocLocked
     187   0.6%  94.0%      187   0.6% runtime.aeshashstr
     183   0.6%  94.6%     1137   3.9% runtime.mallocgc
     127   0.4%  95.0%      988   3.4% math.log10

令人惊讶的是, map 访问似乎是瓶颈。有没有人经历过这个。还有什么其他键值数据结构可以用来避免这个瓶颈?所有 map 访问都在下面给出的以下代码中完成:

func (nb *Classifier) calcProbs(data string) *BoundedPriorityQueue{
    probs := &BoundedPriorityQueue{} 
    heap.Init(probs)

    terms := strings.Split(data, " ")
    for class, prob := range nb.classProb{
        condProb := prob
        clsProbs := nb.model[class]
        for _, term := range terms{
            termProb := clsProbs[term]
            if termProb != 0{
                condProb += math.Log10(termProb)
            }else{
                condProb += -6 //math.Log10(0.000001)
            }
        }
       entry := &Item{
            value: class,
            priority: condProb,
        }
        heap.Push(probs,entry)
    }
    return probs
}

map 是 nb.classProb,它是 map[string]float64 而 nb.model 是类型的嵌套 map

map[string]map[string]float64

最佳答案

除了@tomwilde 所说的之外,另一种可能 加速算法的方法是字符串驻留。也就是说,如果您提前知道 key 的域,则可以完全避免使用映射。我写了一个小包可以做 string interning给你。

关于data-structures - Golang 中的 map 访问瓶颈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21054116/

相关文章:

Java 作业 MaxSumTest

java - 如何使用迭代器 java 将 JSONObject 转换为新 Map 的所有键

python - 无法在 Python 中打印 Trie 中的节点

c - 使用堆栈实现根据最后更新日期跟踪所有文件

java - 了解家庭作业

go - 如何将动态 YAML 解码为 Go 中字符串 -> 字符串 -> 结构的映射?

go - 使用特定数字类型而不是其他数字类型意味着什么

mysql - 指向 MySQL 查询抽象接口(interface)的指针片段

java - 泛型对执行时间的影响

java - Java 1.8中HashMap的HashMap检索