Search code examples
gotypescasting

Performance impact on base type to custom type conversion


does type conversion from base to custom (or custom to base) has negative impacts on performance?

Simple and common scenario.

I have a package B where, for merely syntax reason, I've used some custom types like:

package B

type MyStringType string
type MyInt64Type int64
type MyIntType int64


var StringVar MyStringType
var Int64Var MyInt64Type 
var IntVar MyIntType

StringVar = "hello"
Int64Var = 10
IntVar = 20

Now, I have to use data from package B in my package A, where I need to compare variables but with type conversion (obviously):

package A

import "project/B"

var string_var string
var int64_var int64
var int_var int

string_var = "hi"
int64_var = 100
int_var = 1000


//base to custom

if B.MyStringType(string_var) == B.StringVar {
    fmt.Println("Equal")
}

if B.MyInt64Type(int64_var) == B.Int64Var {
    fmt.Println("Equal")
}

if B.MyIntType(int_var) == B.IntVar{
    fmt.Println("Equal")
}



//custom to base

if string(B.StringVar) == string_var {
    fmt.Println("Equal")
}

if int64(B.Int64Var) == int64_var {
    fmt.Println("Equal")
}

if int(B.IntVar) == int_var {
    fmt.Println("Equal")
}

Question: when used massively, like in a thousands of iterations, this type conversion has some performance impact?

Thanks


Solution

  • There is no runtime impact when converting between names for the same type. This is entirely a compile-time feature and produces no additional instructions at runtime.