Does a type assertion / type switch have bad performance / is slow in Go?

前端 未结 6 761
天涯浪人
天涯浪人 2020-12-07 22:04

How slow is using type assertions / type switches in Go, as a method of run-time type discovery?

I\'ve heard that in C/C++ for example, discovering types at run time

6条回答
  •  我在风中等你
    2020-12-07 23:04

    In your

    switch v := anything.(type) {
        case SomeCustomType:
            fmt.Println(v)
    ...
    

    if you need not SomeCustomType.Fields or methods like in fmt.Println(v), doing

    switch anything.(type) { //avoid 'v:= ' interface conversion, only assertion
        case SomeCustomType:
            fmt.Println("anything type is SomeCustomType", anything)
    ...
    

    should be approximately two times faster

提交回复
热议问题