map [string] interface {}在golang中映射[string]字符串的速度是否更快?或"strconv"功能太慢?

pym*_*ymd 3 interface map go

我在golang做一个url fetcher.我是新来golang,不知道interace {}前面键入并因此使用map[string]string我的args_hash {} (一般哈希参数传递给我的提取程序例如time,date,site-path等).但是,我后来才知道interface{}类型并改变了我map的意思map[string]interface{}.

我的fetcher里面有各种各样的功能args_hash{}.早些时候,我不得不转换应该是整数的args(但由于使用和的整数限制而传递为字符串. 例如map[string]string)strconv.Atoi()stuff

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)
}
Run Code Online (Sandbox Code Playgroud)

我的方法提前几次做了这个,并且args_hash{}在它们之间多次修改了它.

但从现在开始我转向使用

args_hash map[string]interface{}
Run Code Online (Sandbox Code Playgroud)

我不再这样做了.

使用时map[string]string,获取10个特定网址的时间约为23秒,但是map[string]interface{}这已减少到接近一半(约12-13秒).

可能是什么原因?

kos*_*tix 5

我怀疑你可能来自动态语言 - 比如JavaScriptPerl- 缺乏对"结构"的支持(例如在C语言意义上),所以你试图使用地图(你称之为"哈希")而不是Go struct,并将指针传递给struct的实例.

所以我会像这样修改你的代码:

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)
Run Code Online (Sandbox Code Playgroud)