Go Alias ​​Overhead

I am writing vector.go as part of my program. It provides a three-dimensional vector structure and some vector operations.

For symmetry with the generic vector type, I would like to specify the scalar type:

 type scalar float64 

I like it because I do not have to indicate the accuracy of my scalars every time. The fact that they are 64-bit is a part that I would prefer to specify only once.

The only problem is that I know that this is not like typedef in C. It seems like this is happening behind the scenes. My question is: will this lead to overhead ? If so, when and how much? Can I use this when performance is absolutely important? (Suppose I would replace every occurrence of float64 with scalar and convert literals like scalar(1.0) .)

+4
source share
1 answer

First of all, there is no need to translate literals. x = 1.0 same as x = scalar(1.0) if x already has a type scalar.

There is no such thing as a custom type alias in Go. In Go, bytes and uint8 (which are built-in types) are considered aliases of each other. These are two names for the same type. Float64 and scalar are not the same. The values ​​of float64 and scalar must be converted between themselves using something like s = scalar(f) , while bytes and uint8 do not.

However, such conversions have no overhead. Types are used at compile time to ensure that the code is correct, but do not affect runtime performance. Execution is only affected if you make type statements or use reflection. However, these differences affect logic, not performance.

Can I use this when performance is absolutely critical?

Yes

+10
source

Source: https://habr.com/ru/post/1490405/


All Articles