Generics, allocation in switch

155 views
Skip to first unread message

Slawomir Pryczek

unread,
Jun 14, 2026, 4:57:41 AM (4 days ago) Jun 14
to golang-nuts
Hey guys,

I have a generic function:

func GetParam[T string | int | float64 | json.Number](pp ParsedParams, key string) (T, bool) {
    var zero T
    ...
    switch any(zero).(type) {

It's a simple helper to get a value from a union-like struct. However, I've been told that the any(zero).(type) call causes a heap allocation on every invocation — is that a significant performance concern when the function is called several thousand times per second? Would it be better to replace it with four separate typed functions? Is there some better way?

Thanks

Axel Wagner

unread,
Jun 14, 2026, 6:38:26 AM (4 days ago) Jun 14
to Slawomir Pryczek, golang-nuts
Pretty sure you've just been misinformed: https://go.dev/play/p/Vl6KGv4Nog7
The compiler knows that you don't do anything with `any(zero)`, so no need to move it to the heap.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/5f5330e5-0840-40fc-bb67-6f03b243f9e1n%40googlegroups.com.

Jason E. Aten

unread,
Jun 14, 2026, 9:58:39 PM (3 days ago) Jun 14
to golang-nuts
Also you can pass special flags to the compiler to see if, under different circumstances, your variables are or are not escaping to the heap. So you don't have to guess what the escape analysis decided. You can check for yourself. For example: go build -gcflags="-m -l" blah.go

Reply all
Reply to author
Forward
0 new messages