Thanks in advance.
Ask HN: What Is More Compute Efficient Between Golang's If and Switch Statements
1–6 of 6 posts
Re: Ask HN: What Is More Compute Efficient Between Golang's If and Switch Statements
#2compilers are usually optimizing these kind of statements so they end up similar or identical
if you wanna be sure, make two loops running a few million times with random if else / switches and time them
Re: Ask HN: What Is More Compute Efficient Between Golang's If and Switch Statements
#3it's unlikely that there is a difference compilers are usually optimizing these kind of statements so they end up similar or identical if you wanna be sure, make two loops running a few million times with random if else / switches and time them
Re: Ask HN: What Is More Compute Efficient Between Golang's If and Switch Statements
#4it's unlikely that there is a difference compilers are usually optimizing these kind of statements so they end up similar or identical if you wanna be sure, make two loops running a few million times with random if else / switches and time them
If you want to be sure, you have to benchmark your production code with production data.
Look at the generated machine code may also help, but can be difficult, as the generated code may be different, but of similar performance, and judging whether two instruction sequences have similar performance is hard on modern hardware, with its out-of-order executing, multiple layers of caches, etc.
Re: Ask HN: What Is More Compute Efficient Between Golang's If and Switch Statements
#5Re: Ask HN: What Is More Compute Efficient Between Golang's If and Switch Statements
#6You can find out for yourself using the Compiler Explorer (godbolt): https://godbolt.org/z/qrYGzMjWd Looks to me as if If is more efficient here.