Overhead of interface{} cast is near to zero, yes?

hi,
i wrote a simple benchmark,
result is near to zero both work under 11ns

is it correct ?? overhead of interface{} cast to struct is near zero ??

import (
	"fmt"
	"testing"
)

type Message struct {
	fname string
	lname string
	age   int
}

func BenchmarkNormal(b *testing.B) {
	msgs := FakeMessage(500)
	for i := 0; i < b.N; i++ {
		bench_normal(msgs)
	}
}
func BenchmarkCheckCast(b *testing.B) {
	msgs := FakeInterface(500)
	for i := 0; i < b.N; i++ {
		bench_checkcast(msgs)
	}
}

func bench_normal(arr []*Message) {
	for i := 0; i <= len(arr)-1; i++ {
		vd := arr[i].fname + arr[i].lname
		if i == len(arr) {
			fmt.Println("==> ", vd)
		}
	}
}

func bench_checkcast(arr []interface{}) {

	for i := 0; i <= len(arr)-1; i++ {
		switch entry := arr[i].(type) {
		case *Message:
			vd := entry.fname + entry.lname
			if i == len(arr) {
				fmt.Println("==> ", vd)
			}
		default:
			panic("Not Found")
		}
	}
}

func FakeMessage(demand int) []*Message {
	messages := make([]*Message, demand)
	for i := 0; i < demand; i++ {
		messages[i] = &Message{
			fname: "Danyal",
			lname: "Mh",
			age:   23,
		}
	}
	return messages
}

func FakeInterface(demand int) []interface{} {
	messages := make([]interface{}, demand)
	for i := 0; i < demand; i++ {
		msg := &Message{
			fname: "Danyal",
			lname: "Mh",
			age:   23,
		}
		messages[i] = msg
	}
	return messages
}

There’s very little work done in a type assertion. It doesn’t convert or copy anything. https://www.sohamkamani.com/golang/type-assertions-vs-type-conversions/#type-assertions. It just extracts the value from the interface object if the type matches.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.