Skip to content

Commit bb731b2

Browse files
committed
crypto/cipher: optimize safeXORBytes
Optimize safeXORBytes based on this conversation: #35381
1 parent 3b5eec9 commit bb731b2

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/crypto/cipher/xor_generic.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
package cipher
88

99
import (
10+
"encoding/binary"
1011
"runtime"
1112
"unsafe"
1213
)
@@ -63,7 +64,19 @@ func fastXORBytes(dst, a, b []byte, n int) {
6364

6465
// n needs to be smaller or equal than the length of a and b.
6566
func safeXORBytes(dst, a, b []byte, n int) {
66-
for i := 0; i < n; i++ {
67+
// Load multiple bytes so the compiler can recognize
68+
// and optimize them into single multi-byte loads
69+
w := n / wordSize
70+
if w > 0 {
71+
for i := 0; i < w; i++ {
72+
offset := i * wordSize
73+
k := binary.LittleEndian.Uint64(a[offset:])
74+
v := binary.LittleEndian.Uint64(b[offset:])
75+
binary.LittleEndian.PutUint64(dst[offset:], k^v)
76+
}
77+
}
78+
79+
for i := (n - n%wordSize); i < n; i++ {
6780
dst[i] = a[i] ^ b[i]
6881
}
6982
}

0 commit comments

Comments
 (0)