Map vs switch for lookup tables

870 views
Skip to first unread message

JohnGB

unread,
Dec 26, 2014, 6:34:02 AM12/26/14
to golan...@googlegroups.com
I'm in the process of writing a package to validate and look up language and region codes, and I'm trying to decide on which structure to use for this.  The tables will have 200 - 500 rows. 

I tested various options and benchmarked them to get a feel for which would be best, and (using a table with ±200 rows) I've narrowed it down to two options.

1) Use a long switch statement.  This has the advantage of not needing to have a data structure in memory, and is fairly fast (67-87 ns/op).

2) Use a map which is preloaded in memory.  This is a bit faster (38-50 ns/op), but has a long (relative time) to load up in memory of ±38 µs.

So, option 1 seems better for situations where it's called less often, and 2 seems better for situations where a longer setup time is okay, but the function is called more often.  I'm tempted to go with the switch method, but before I commit to that, I'd like feedback on it, or pointers to any other examples or methods that have been well executed.

~ John

Kevin Malachowski

unread,
Dec 26, 2014, 10:03:09 AM12/26/14
to golan...@googlegroups.com
Do you have a code sample? What is the type of the key for the map? If its a string, what sort of lengths are the strings?

Also, is this all your program does? Unless it calls this function in a tight loop without doing IO it might not even matter.

rjeczalik

unread,
Dec 26, 2014, 10:09:02 AM12/26/14
to JohnGB, golang-nuts
On 26 December 2014 at 12:34, JohnGB <jgbe...@gmail.com> wrote:
> (...)
> I'm tempted to go with the switch method, but before I commit to that, I'd like feedback on it,
> or pointers to any other examples or methods that have been well executed.

If you generated code for lookup structures you could switch the implementation in future in no time.

For example time package uses map, codegen tool:


and its output:

Reply all
Reply to author
Forward
0 new messages