doujian4752 2018-08-16 20:46
浏览 407
已采纳

在sync.Map中加载或存储,而无需每次都创建新结构

Is it possible to LoadOrStore into a Go sync.Map without creating a new structure every time? If not, what alternatives are available?

The use case here is if I'm using the sync.Map as a cache where cache misses are rare (but possible) and on a cache miss I want to add to the map, I need to initialize a structure every single time LoadOrStore is called rather than just creating the struct when needed. I'm worried this will hurt the GC, initializing hundreds of thousands of structures that will not be needed.

In Java this can be done using computeIfAbsent.

  • 写回答

2条回答 默认 最新

  • dongxietao0263 2018-08-16 22:47
    关注

    Package sync

    import "sync"
    

    type Map

    Map is like a Go map[interface{}]interface{} but is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.

    The Map type is specialized. Most code should use a plain Go map instead, with separate locking or coordination, for better type safety and to make it easier to maintain other invariants along with the map content.

    The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a Map may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.


    The usual way to solve these problems is to construct a usage model and then benchmark it.

    For example, since "cache misses are rare", assume that Load wiil work most of the time and only LoadOrStore (with value allocation and initialization) when necessary.

    $ go test map_test.go -bench=. -benchmem
    BenchmarkHit-4     2     898810447 ns/op        44536 B/op        1198 allocs/op
    BenchmarkMiss-4    1    2958103053 ns/op    483957168 B/op    43713042 allocs/op
    $
    

    map_test.go:

    package main
    
    import (
        "strconv"
        "sync"
        "testing"
    )
    
    func BenchmarkHit(b *testing.B) {
        for N := 0; N < b.N; N++ {
            var m sync.Map
            for i := 0; i < 64*1024; i++ {
                for k := 0; k < 256; k++ {
    
                    // Assume cache hit
                    v, ok := m.Load(k)
                    if !ok {
                        // allocate and initialize value
                        v = strconv.Itoa(k)
                        a, loaded := m.LoadOrStore(k, v)
                        if loaded {
                            v = a
                        }
                    }
                    _ = v
    
                }
            }
        }
    }
    
    func BenchmarkMiss(b *testing.B) {
        for N := 0; N < b.N; N++ {
            var m sync.Map
            for i := 0; i < 64*1024; i++ {
                for k := 0; k < 256; k++ {
    
                    // Assume cache miss
                    // allocate and initialize value
                    var v interface{} = strconv.Itoa(k)
                    a, loaded := m.LoadOrStore(k, v)
                    if loaded {
                        v = a
                    }
                    _ = v
    
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误