What will work faster — generics or empty interfaces?
sobes.tech AI
Answer from AI
In Go, the performance of generics and empty interfaces (interface{}) depends on the specific use case.
-
Generics allow compiling type-safe code where types are known at compile time, which can lead to more efficient machine code and fewer type conversions at runtime.
-
Empty interface (
interface{}) is a dynamic type that requires additional type information and can lead to type assertion operations at runtime, which may be slower.
Therefore, in most cases, generics perform faster than using empty interfaces, especially when there are many type operations, as they avoid the overhead of dynamic typing.
Example:
func SumIntsOrFloats[T int | float64](slice []T) T {
var sum T
for _, v := range slice {
sum += v
}
return sum
}
Here, the compiler generates code for specific types, which is more efficient than working with interface{} and type assertions.