@Jan Thank you for the feedback. I will try with a higher number of constants. By the way, my benchmark tries all the path:
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 I did not add it since it was not the original question ^^ But why can't we have the check and a switch? Here is the 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) + ")" } } Le mardi 18 février 2020 14:06:14 UTC+4, Jan Mercl a écrit : > > On Tue, Feb 18, 2020 at 10:37 AM Vincent Blanchon > <blancho...@gmail.com <javascript:>> wrote: > > > @Jan, yes definitely. By the way, here are some numbers from a benchmark > I made with 20 constants: > > > > name time/op > > Stringer-4 4.16ns ± 2% > > > > StringerWithSwitch-4 3.81ns ± 1% > > > > StringerWithMap-4 28.60ns ± 2% > > 20 is a small number. In general, measuring things where one iteration > is in single digit nanoseconds can be misleading as discussed earlier. > The probably most important thing is how a chosen implementation > scales. To measure that, I suggest to make the number of the constants > in hundreds, if not thousands and having the loop exercise all the > paths, so the branch predictor cannot learn a single, happy one. In > any case, it's much safer to shift the time/op to at least > microseconds, otherwise the overhead of the test per se becomes > comparable to the measured thing and it just adds noise at minimum. > > > @Pierre, the compilation check can also be done if we do not have a > slice. In my example with the switch, I still kept the compilation check. > > I can't find any compile time check in your code (the one using the > switch) that can detect a constant has changed its value since > stringer was run. > -- 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+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ee65758b-274f-4e20-b6ef-7a449b55221b%40googlegroups.com.