Skip to content

Instantly share code, notes, and snippets.

@aaronjwood
Created November 2, 2016 03:42
Show Gist options
  • Save aaronjwood/f017dba35d5fa5f666c41877b179dc45 to your computer and use it in GitHub Desktop.
Save aaronjwood/f017dba35d5fa5f666c41877b179dc45 to your computer and use it in GitHub Desktop.
Comparing variable swap with XOR and with temporary variable.
package main
func Swap(a, b int) int {
a = a ^ b
b = b ^ a
a = a ^ b
return a
}
func Temp(a, b int) int {
temp := a
a = b
b = temp
return a
}
package main
import (
"testing"
)
func BenchmarkSwap(b *testing.B) {
for n := 0; n < b.N; n++ {
Swap(50, 200)
}
}
func BenchmarkTemp(b *testing.B) {
for n := 0; n < b.N; n++ {
Temp(50, 200)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment