Skip to content

Instantly share code, notes, and snippets.

@aisk
Created April 26, 2020 16:57
Show Gist options
  • Save aisk/92726ec3366b4ba979693ec58ec2abe6 to your computer and use it in GitHub Desktop.
Save aisk/92726ec3366b4ba979693ec58ec2abe6 to your computer and use it in GitHub Desktop.
go dispatch bench
package main
import (
"fmt"
"strconv"
"unsafe"
)
const (
typeInt = iota
typeString
)
type object struct {
typ int
}
type intObject struct {
object
value int
}
func newIntObject(value int) *object {
obj := &intObject{
object{typeInt},
value,
}
return &(obj.object)
}
func (o *object) String() string {
switch o.typ {
case typeInt:
return strconv.Itoa(((*intObject)(unsafe.Pointer(o))).value)
case typeString:
return ((*stringObject)(unsafe.Pointer(o))).value
default:
panic("not implementet string method")
}
}
type stringObject struct {
object
value string
}
func newStringObject(value string) *object {
obj := &stringObject{
object{typeString},
value,
}
return &(obj.object)
}
func add(lhs, rhs *object) *object {
switch lhs.typ {
case typeInt:
lhsValue := ((*intObject)(unsafe.Pointer(lhs))).value
switch rhs.typ {
case typeInt:
rhsValue := ((*intObject)(unsafe.Pointer(rhs))).value
return newIntObject(lhsValue + rhsValue)
case typeString:
rhsValue := ((*stringObject)(unsafe.Pointer(rhs))).value
return newStringObject(strconv.Itoa(lhsValue) + rhsValue)
default:
panic("not implemented")
}
case typeString:
lhsValue := ((*stringObject)(unsafe.Pointer(lhs))).value
switch rhs.typ {
case typeInt:
rhsValue := (*intObject)(unsafe.Pointer(rhs)).value
return newStringObject(lhsValue + strconv.Itoa(rhsValue))
case typeString:
rhsValue := (*stringObject)(unsafe.Pointer(rhs)).value
return newStringObject(lhsValue + rhsValue)
}
panic("not implemented")
}
panic("not implemented")
}
func main() {
i1 := newIntObject(3)
fmt.Printf("i1: %s\n", i1)
i2 := newIntObject(39)
fmt.Printf("i2: %s\n", i2)
s1 := newStringObject("hello")
fmt.Printf("s1: %s\n", s1)
s2 := newStringObject("world")
fmt.Printf("s2: %s\n", s2)
o1 := add(i1, i2)
fmt.Printf("o1(i1+i2): %s\n", o1)
o2 := add(i1, s1)
fmt.Printf("o2(i1+s1): %s\n", o2)
o3 := add(s1, i1)
fmt.Printf("o3(s1+i1): %s\n", o3)
o4 := add(s1, s2)
fmt.Printf("o4(s1+s2): %s\n", o4)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment