pymd
pymd

Reputation: 4401

Is map[string]interface{} faster that map[string]string in golang? or are "strconv" functions too slow?

I'm making a url fetcher in golang. I'm new to golang and didn't know about interace{} type earlier and was hence using map[string]string for my args_hash{} (a general hash to pass arguments to my fetcher e.g.time,date,site-path etc). However, I learned later about interface{} type and changed my map to map[string]interface{}.

Various functions inside my fetcher use args_hash{}. Earlier, I had to convert the args that were supposed to be integers (but passed as string due to limitations of map[string]string) to integers using strconv.Atoi() and stuff.
e.g.

func my_def(args_hash{} map[string]string){
    url_count := strconv.Atoi(args_hash["url_count"])
   // ... use url count
    .
    .
   // ......successful url count calculated
   args_hash["success_url_count"] = strconv.Itoa(success_count)
}

My methods did this several times earlier and also passed this modified args_hash{} between them several times.

But since now I've shifted to using

args_hash map[string]interface{}

I don't do this anymore.

With map[string]string, the time taken to fetch 10 particular urls was around 23 sec, however with map[string]interface{} this has reduced to nearly half (around 12-13 sec).

What might be the reason for this?

Upvotes: 3

Views: 5356

Answers (1)

kostix
kostix

Reputation: 55473

I suspect you might be coming from a dynamic language — like JavaScript or Perl — which lack support for "structures" (in the C-language sense, for instance) and so you're trying to use a map (what you call "a hash") instead of a Go struct, and passing around pointer to the instance of a struct.

So I'd rework your code like this:

type FetcherArgs struct {
    OkUrlCount int
    UrlCount int
    FooBar string
    // ... and so on
}

func my_def(args *FetcherArgs) {
    args.OkUrlCount += 1
    // ...
    fmt.Printf("%v\n", args.UrlCount)
    // ...
}

var args = FetchArgs{UrlCount: 42, FooBar: "Life, the Universe and Everything"}
my_def(&args)

Upvotes: 5

Related Questions