const _Pill_name = "PlaceboAspirinIbuprofen"
var _Pill_index = [...]uint8{0, 7, 14, 23}
func (i Pill) String() string {
if i < 0 || i >= Pill(len(_Pill_index)-1) {
return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}
func (i Pill) String() string {
switch i {
case 0: return "Placebo"
case 1: return "Aspirin"
case 2: return "Ibuprofen"
case 3: return "Paracetamol"
default: return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
> A simpler and faster way again would be to use a map.
> https://play.golang.org/p/ntjhesMsSA9
I don't see how could be map lookup possibly faster than slice
indexing. Have you some measurements to share?
name time/op
Stringer-4 4.16ns ± 2%
StringerWithSwitch-4 3.81ns ± 1%StringerWithMap-4 28.60ns ± 2%
func BenchmarkStringerWithSwitch(b *testing.B) {
for i := 0; i < b.N ; i++ {
p := Pill(i%20)
_ = p.String()
}
}
I can't find any compile time check in your code
package main
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Placebo-0]
_ = x[Aspirin-1]
_ = x[Ibuprofen-2]
}
func (i Pill) String() string {
switch i {
case 0: return "Placebo"
case 1: return "Aspirin"
case 2: return "Ibuprofen"
case 3: return "Paracetamol"
default: return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
I did not add it since it was not the original question ^^But why can't we have the check and a switch?
Stringer-4 4.96ns ± 0%
StringerWithSwitch-4 4.99ns ± 1%
StringerWithMap-4 30.40ns ± 0%
There's no question the generated method is ugly. That's OK, though, because humans don't need to work on it; machine-generated code is often ugly. It's working hard to be efficient. All the names are smashed together into a single string, which saves memory (only one string header for all the names, even if there are zillions of them). Then an array,_Pill_index
, maps from value to name by a simple, efficient technique. Note too that_Pill_index
is an array (not a slice; one more header eliminated) ofuint8
, the smallest integer sufficient to span the space of values. If there were more values, or there were negatives ones, the generated type of_Pill_index
might change touint16
orint8
: whatever works best.
--
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 on the web visit https://groups.google.com/d/msgid/golang-nuts/69db18c0-31a4-4d52-94c6-a168ef815e0a%40googlegroups.com.