英文:
Overhead of type "alias" in Go
问题
我正在编写vector.go
作为我的程序的一部分。它提供了一个三维的vector
结构和一些向量操作。
为了与一般的vector
类型保持对称,我想提供一个scalar
类型:
type scalar float64
我喜欢这样做是因为我不需要每次都指定我的标量的精度。它们是64位的事实是一个细节,我宁愿只指定一次。
唯一的问题是我知道这不像C中的typedef
。似乎有更多的事情发生在幕后。我的问题是:这会产生任何开销吗?如果有,那么何时和多少?在性能绝对关键的情况下,我可以使用它吗?(假设我将每个float64
的出现都替换为scalar
并转换文字,例如scalar(1.0)
。)
英文:
I'm writing vector.go
as a part of my program. It provides a three-dimensional vector
struct and some vector operations.
For symmetry with the general vector
type, I would like to provide a scalar
type:
type scalar float64
I like this because there's no reason I should specify the precision of my scalars each and every time. The fact that they are 64-bit is a detail which I would rather specify only once.
The only problem is that I know this is not like typedef
in C. There seems to be more going on behind the scenes then that. My question: will this incur any overhead? If so, when and how much? Can I use this when performance is absolutely critical? (Assume that I will replace every occurrence of float64
with scalar
and convert literals, e.g, scalar(1.0)
.)
答案1
得分: 12
首先,没有必要转换字面量。假设x已经具有标量类型,x = 1.0
与x = scalar(1.0)
是相同的。
在Go中,没有用户定义的类型别名。在Go中,byte和uint8(它们是内置类型)被认为是彼此的别名。它们是同一类型的两个名称。Float64和scalar不是相同的类型。float64和scalar的值需要使用类似s = scalar(f)
的方式进行转换,而byte和uint8则不需要。
然而,这样的转换没有额外的开销。类型在编译时强制执行以确保代码正确性,但不会影响执行期间的性能。只有在进行类型断言或使用反射时,执行才会受到影响。然而,这些差异影响的是逻辑,而不是性能。
> 当性能非常关键时,我可以使用这个吗?
可以。
英文:
First of all, there is no need to convert literals. x = 1.0
is the same as x = scalar(1.0)
assuming x already has the type scalar.
In Go, there is no such thing as a user defined type alias. In Go, byte and uint8 (which are builtin types) are considered aliases of each other. They are two names for the same type. Float64 and scalar are not the same type. Values of float64 and scalar need to be converted between each other using something like s = scalar(f)
while byte and uint8 do not.
However, such conversions have no overhead. The types are enforced at compile time for code correctness but does not affect performance during execution. Execution is only affected if you do type assertions or use reflection. However, these differences affect logic, not performance.
> Can I use this when performance is absolutely critical?
Yes
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论