Created
October 23, 2023 08:11
-
-
Save piersy/62c9cddca83055a7968c92df8f274585 to your computer and use it in GitHub Desktop.
Performance of modulo or bit operation in golang for checking even?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func BenchmarkCheckEven(b *testing.B) { | |
nums := make([]uint64, 10000) | |
for i := 0; i < len(nums); i++ { | |
bytes := make([]byte, 8) | |
_, err := rand.Read(bytes) | |
require.NoError(b, err) | |
val := binary.BigEndian.Uint64(bytes) | |
nums[i] = val | |
} | |
results := make([]bool, 10000) | |
b.Run("modulo", func(b *testing.B) { | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
for i := 0; i < len(nums); i++ { | |
if nums[i]%2 == 0 { | |
results[i] = true | |
} | |
} | |
} | |
}) | |
b.Run("bitop", func(b *testing.B) { | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
for i := 0; i < len(nums); i++ { | |
if nums[i]&1 == 0 { | |
results[i] = true | |
} | |
} | |
} | |
}) | |
} | |
It turns out they are the same, since they compile to the exactly the same three operations in assembly. | |
MOVQ (SI)(R8*8), R9 | |
BTL $0, R9 | |
JCS 126 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment