Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: optimize pkcs7Padding #212

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

kvii
Copy link

@kvii kvii commented Jan 22, 2025

把 bytes.Repeat 改成 for 循环的话效率会高一倍多,内存占用也会少一点。

package playground

import (
	"bytes"
	"testing"
)

func BenchmarkOld(b *testing.B) {
	for i := 0; i < b.N; i++ {
		src := []byte("0123456789abcdef")
		src = pkcs7PaddingOld(src)
		_ = src
	}
}

func BenchmarkNew(b *testing.B) {
	for i := 0; i < b.N; i++ {
		src := []byte("0123456789abcdef")
		src = pkcs7PaddingNew(src)
		_ = src
	}
}

const BlockSize = 16

func pkcs7PaddingOld(src []byte) []byte {
	padding := BlockSize - len(src)%BlockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(src, padtext...)
}

func pkcs7PaddingNew(src []byte) []byte {
	padding := BlockSize - len(src)%BlockSize
	for i := 0; i < padding; i++ {
		src = append(src, byte(padding))
	}
	return src
}
> go test -benchmem -run=^$ -bench ^(BenchmarkOld|BenchmarkNew)$ github.com/kvii/playground

goos: darwin
goarch: arm64
pkg: github.com/kvii/playground
cpu: Apple M1 Pro
BenchmarkOld-10    	20169958	        53.38 ns/op	      48 B/op	       2 allocs/op
BenchmarkNew-10    	54074353	        22.81 ns/op	      32 B/op	       1 allocs/op
PASS
ok  	github.com/kvii/playground	3.581s

@kvii kvii changed the title feat: optimize pkcsPadding feat: optimize pkcs7Padding Jan 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant