@Brian, this code is generated by the stringer command based on this 
code: https://play.golang.org/p/JNfRC5TZYlo
@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%


Map is definitely the slowest one.

@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. This 
check just use the constants, no relation with the "String()" function.


Le mardi 18 février 2020 13:20:01 UTC+4, pierr...@gmail.com a écrit :
>
> The const/slice implementation should be faster as Jan said.
>
> Note that there is also a blank function that fails at compile time if 
> items have been added or changed and stringer has not been rerun since.
> The const/slice implementation allows for that (useful!) check.
>
>
> Le mardi 18 février 2020 07:42:41 UTC+1, Vincent Blanchon a écrit :
>>
>> Hello,
>>
>> I was wondering why the stringer command has been implemented that way:
>>
>> 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]]
>> }
>>
>>
>>
>> When it could be simpler and faster with a simple enum:
>>
>> 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) + ")"
>>    }
>> }
>>
>>
>> After running a benchmark with a higher number of values (20), the enum 
>> is always faster. I also was surprised to see the binary is not bigger 
>> (maybe it will be with more values).
>>
>> Does someone know what advantages the current design brings?
>>
>

-- 
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/e99ed426-a5ff-4582-9e6a-89143812ee46%40googlegroups.com.

Reply via email to