Question

Would this be an appropriate way to implement an lookup table in Go? Are there any better ways? I'd like this to work if the entries happened to be nonconsecutive.

func LookupRpMax(val uint8) float64 {
    rpMaxRegisters := map[uint8]float64 {
        0x00 : 3926991,
        0x01 : 3141593,
        0x02 : 2243995,
        0x03 : 1745329,
        0x04 : 1308997,
        0x05 : 981748,
        0x06 : 747998,
        0x07 : 581776,
        0x08 : 436332,
        0x09 : 349066,
        0x0A : 249333,
        0x0B : 193926,
        0x0C : 145444,
        0x0D : 109083,
        0x0E : 83111,
        0x0F : 64642,
        0x10 : 48481,
        0x11 : 38785,
        0x12 : 27704,
        0x13 : 21547,
        0x14 : 16160,
        0x15 : 12120,
        0x16 : 9235,
        0x17 : 7182,
        0x18 : 5387,
        0x19 : 4309,
        0x1A : 3078,
        0x1B : 2394,
        0x1C : 1796,
        0x1D : 1347,
        0x1E : 1026,
        0x1F : 798,
    }
    return rpMaxRegisters[val];

}

Was it helpful?

Solution

You can use a flat slice if you like - then you just have null/0 for entries that don't have a entry. That approach would be bad if your non-consecutive values can range to very high values.

Using this code: http://play.golang.org/p/gLni-BzMKy

I got these results after running 100,000,000 indexes on a slice and map: Map: 3062 ms Slice: 56 ms

That being said - the speed difference shouldn't matter in almost any real world use case. I would just use a map personally.

Edit: And I agree with the other comment that says to initialize the map outside the function so it only has to be constructed once and not on every call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top