英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论