I suppose the difference between int and int32 comes from the behavior of the modulo strength reduction mechanism.
With int (=int64), n%100000000 is compiled as: MOVQ $0xabcc77118461cefd, AX MOVQ #n, CX IMULQ CX ADDQ CX, DX SARQ $0x1a, DX MOVQ CX, BX SARQ $0x3f, CX SUBQ CX, DX IMULQ $0x5f5e100, DX, CX SUBQ CX, BX MOVQ BX, #result With int32, n%100000000 is compiled as: MOVL #n, AX MOVSXD AX, CX MOVL $-0x543388ee, DX IMULQ CX, DX SARQ $0x3a, DX SARQ $0x3f, CX SUBL CX, DX IMULL $0x5f5e100, DX, CX SUBL CX, AX MOVL AX, #result With int32, there are a bit less instructions, and the last multiplication is using a 32 bits instruction. I think this accounts for the slightly better performance, but it is likely dependent on the CPU model. Btw, if you change to uint32, you will get even better performance, because in that case, the strength reduction gives: MOVL $-0x543388ee, AX MOVL #n, CX IMULQ CX, AX SHRQ $0x3a, AX IMULL $0x5f5e100, AX, AX SUBL AX, CX MOVL CX, #result In the Go compiler, I believe these optimizations are implemented in: https://github.com/golang/go/blob/master/src/cmd/compile/internal/ssa/gen/generic.rules You may want to search for Div/Mod related transformations. Best regards, Didier. Le vendredi 26 mars 2021 à 00:21:15 UTC+1, Isaac Gouy a écrit : > On Thursday, March 25, 2021 at 12:31:25 PM UTC-7 Didier wrote: > >> I believe this is simply due to the 64 bits integer division. >> >> 1. Contrary to Java or most C implementations int is 64 bits with Go on >> AMD64, and not 32 bits. Integer division on 64 bits is more expensive than >> for 32 bits. >> 2. When array_length is known at compile time, the compiler can replace >> the integer division done for % with cheaper operations. >> > > And now compile-time-constant program with explicit int32 and > run-time-value program with explicit int64. > > In summary — > > compile-time-constant program > int 3m3.225s > int32 2m43.404s > int64 3m3.240s > > run-time-value program > int 18m20.737s > int32 6m57.880s > int64 18m21.020s > > Hmmm what explains the difference for the compile-time-constant program > between int and explicit int32 ? > > -- 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/48c80e44-056a-41b5-8536-2539cff8a114n%40googlegroups.com.