5 ms·
It may be useful to have a look at the assembly. There's probably no instruction corresponding to the cast, you just get a different arithmetic instruction that
by anonymoushn 4y ago
It may be useful to have a look at the assembly. There's probably no instruction corresponding to the cast, you just get a different arithmetic instruction that uses the bottom X bits. For a comparison between code with and without a cast between signed and unsigned ints of the same width, I would expect exactly the same instructions to be used.
- gbin 4y agoI agree... The compiler can make a lot of assumptions on such a simple operation, you have to look at the assembly. In other more complex cast cases it might be slower so I would not assume anything.
- tankenmate 4y agoThis may also depend on the architecture, what may be free or close to free on AArch64 may not be the case on x86_64 for example. Also of course, the the relative costs (e.g. 3x for float cast) may be different as well.
- PaulKeeble 4y agoThe line x += int32(i) Produces the assembler line 0x001e 00030 (.\cast_test.go:10) ADDL CX, DX In comparison the code x += i is using 0x001e 00030 (.\cast_test.go:19) ADDQ CX, DX The results are definitely different since the ADDL is for 32 bits and ADDQ is 64 bits and that is how its achieving the cast. Not sure the intent of the benchmark (the cost of a cast) is being captured directly since we have a specialist instruction for add to do the casting. But when you think about it ADDL 0, $Val achieves a cast and its 1 instruction so its not expensive at all and there may be something better than that for explicit casts, I doubt there is worse. Its basically free, I see no performance difference between them and that fits with expectations since casting is just throwing away all the top bits.
- anonymoushn 4y agoThanks. This is what I said I expected, given that int32 and int are different widths.
- Someone 4y agoNot only useful, but required. They have to check that the code is performing the intended operation and, even, that the loop still is there (https://kristerw.blogspot.com/2019/04/how-llvm-optimizes-geometric-sums.html https://kristerw.blogspot.com/2019/04/how-llvm-optimizes-geo... shows how gcc and clang remove some loops. The loops used here have simple forms, too, and could fall to the same type of optimization)