map [byte] int和map [string] int有不同的内存使用量

问题描述 投票:0回答:1

这个问题来自a little simple problem from LeetCode

这个问题与LeetCode问题本身并没有太大关系。但它与两种方法有关,这两种方法在qazxsw poi的类型上只有不同,以解决这个LeetCode问题。


  1. 使用map的第一种方法:
map[byte]int

如何通过LeetCode在线评判:

func romanToInt(s string) int {
    m := map[byte]int{
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    }
    result := 0
    length := len(s)
    last_element := length - 1
    for i := 0; i < last_element; i++ {
        current := m[s[i]]
        next := m[s[i+1]]
        if current < next {
            result -= current
        } else {
            result += current
        }
    }
    result += m[s[last_element]]
    return result
}

  1. 使用✔ Accepted ✔ 3999/3999 cases passed (16 ms) ✔ Your runtime beats 100 % of golang submissions ✔ Your memory usage beats 22 % of golang submissions (3 MB) 的第二种方法:
map[string]int

如何通过LeetCode在线评判:

func romanToInt(s string) int {
    m := map[string]int{
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000,
    }
    result := 0
    length := len(s)
    last_element := length - 1
    for i := 0; i < last_element; i++ {
        current := m[string(s[i])]
        next := m[string(s[i+1])]
        if current < next {
            result -= current
        } else {
            result += current
        }
    }
    result += m[string(s[last_element])]
    return result
}

有人说在线评价:我在1小时的时间间隔内运行了这两个版本超过10次。在✔ Accepted ✔ 3999/3999 cases passed (16 ms) ✔ Your runtime beats 100 % of golang submissions ✔ Your memory usage beats 100 % of golang submissions (3 MB) ,他们达到了22%对100%。

我的期望:

我认为第一个使用memory usage应该更快,更节省内存。

为什么更快:在第二个版本中,我必须每次都将map[byte]int投射到rune。 (但string告诉我这不是一个很大的区别。)

为什么要节省内存:因为compiler explorerbyte更轻。


最后一个问题:

为什么在string有区别? 为什么我的期望错了?

dictionary go memory-management
1个回答
2
投票

对您的代码进行基准测试,memory usageromanToIntStrromanToIntBytromanToIntStr之间的区别并不显着。你的代码romanToIntBytromanToIntStr效率不高。见romanToIntByt


输出:

romanToIntArr

$ go test roman2int_test.go -bench=. -benchmem BenchmarkRomanToIntStr-8 2725520 440 ns/op 0 B/op 0 allocs/op BenchmarkRomanToIntByt-8 2377992 499 ns/op 0 B/op 0 allocs/op BenchmarkRomanToIntArr-8 25643797 42.3 ns/op 0 B/op 0 allocs/op

roman2int_test.go
© www.soinside.com 2019 - 2024. All rights reserved.