On Friday, 20 November 2020 at 09:26:57 UTC christoph...@gmail.com wrote: > A handy feature of bool <-> int conversion is that true is converted to 1 > and any integer different of zero to true. As a consequence, when we write > int(bool(x)) we get 0 when x is 0, and 1 when x is not 0. >
I don't think you've tried this with Go. Playground <https://play.golang.org/p/ZR02eZ_FROn> ./prog.go:9:15: cannot convert x (type int) to type bool It doesn't work the other way either: e.g. int(v ^ v1 != 0) ./go1.go:9:13: cannot convert v ^ v1 != 0 (type untyped bool) to type int > This is to be compared with > > r := v==v1 || v==v2 || v==v3 > > The second form is of course more readable, but will also have a > conditional branch at each ||. > You should compare the generated machine code before saying one is better than the other. If int(bool(x)) worked, it might also have a conditional branch; that is, it would presumably be the same as int(x != 0). In that case, your code becomes int(v^v1 != 0) which may or may not compile to the same code as int(v != v1). To see the assembly language: go build -gcflags -S myprog.go Note that > r := (v^v1)*(v^v2)*(v^v3) risks integer overflow and may give the wrong answer. Playground <https://play.golang.org/p/IAK-20Ypw5_S> Apart from this, I think you're trying to micro-optimise. Do you have code which is measurably affected by the problem you describe, i.e. by actual profiling? Modern processors have optimisations to deal with branches, e.g. speculative execution. Also, if you're dealing with data which is not in cache, then DRAM access is orders of magnitude slower than the CPU - i.e. the CPU cost is almost free compared to the DRAM access cost. -- 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/38d981a1-7579-4cdc-b166-0d6d1b43da8bn%40googlegroups.com.