基本类型到自定义类型转换的性能影响

huangapple go评论61阅读模式
英文:

Performance impact on base type to custom type conversion

问题

类型转换从基本类型到自定义类型(或从自定义类型到基本类型)对性能有负面影响吗?

简单而常见的情况。

我有一个包B,仅仅出于语法原因,我使用了一些自定义类型,例如:

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

现在,我需要在我的包A中使用包B的数据,但我需要进行类型转换才能比较变量(显然):

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


//基本类型到自定义类型

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")
}



//自定义类型到基本类型

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")
}

问题:当大量使用时,比如在成千上万次迭代中,这种类型转换会对性能产生影响吗?

谢谢

英文:

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

答案1

得分: 2

在同一类型的名称之间进行转换时,不会对运行时产生任何影响。这完全是一个编译时的特性,在运行时不会产生额外的指令。

英文:

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.

huangapple
  • 本文由 发表于 2023年3月11日 07:52:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75701943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定