Add benchmark tests and optimize encryption performance

- Introduced comprehensive benchmark tests for NIP-44 and NIP-4 encryption/decryption, including various message sizes and round-trip operations.
- Implemented optimizations to reduce memory allocations and CPU processing time in encryption functions, focusing on pre-allocating buffers and minimizing reallocations.
- Enhanced error handling in encryption and decryption processes to ensure robustness.
- Documented performance improvements in the new PERFORMANCE_REPORT.md file, highlighting significant reductions in execution time and memory usage.
This commit is contained in:
2025-11-02 18:08:11 +00:00
parent b47a40bc59
commit 53fb12443e
9 changed files with 1237 additions and 20 deletions

View File

@@ -139,15 +139,27 @@ func UnmarshalQuoted(b []byte) (content, rem []byte, err error) {
}
func MarshalHexArray(dst []byte, ha [][]byte) (b []byte) {
dst = append(dst, '[')
b = dst
// Pre-allocate buffer if nil to reduce reallocations
// Estimate: [ + (hex encoded item + quotes + comma) * n + ]
// Each hex item is 2*size + 2 quotes = 2*size + 2, plus comma for all but last
if b == nil && len(ha) > 0 {
estimatedSize := 2 // brackets
if len(ha) > 0 {
// Estimate based on first item size
itemSize := len(ha[0]) * 2 // hex encoding doubles size
estimatedSize += len(ha) * (itemSize + 2 + 1) // item + quotes + comma
}
b = make([]byte, 0, estimatedSize)
}
b = append(b, '[')
for i := range ha {
dst = AppendQuote(dst, ha[i], hex.EncAppend)
b = AppendQuote(b, ha[i], hex.EncAppend)
if i != len(ha)-1 {
dst = append(dst, ',')
b = append(b, ',')
}
}
dst = append(dst, ']')
b = dst
b = append(b, ']')
return
}
@@ -156,6 +168,9 @@ func MarshalHexArray(dst []byte, ha [][]byte) (b []byte) {
func UnmarshalHexArray(b []byte, size int) (t [][]byte, rem []byte, err error) {
rem = b
var openBracket bool
// Pre-allocate slice with estimated capacity to reduce reallocations
// Estimate based on typical array sizes (can grow if needed)
t = make([][]byte, 0, 16)
for ; len(rem) > 0; rem = rem[1:] {
if rem[0] == '[' {
openBracket = true
@@ -193,6 +208,9 @@ func UnmarshalHexArray(b []byte, size int) (t [][]byte, rem []byte, err error) {
func UnmarshalStringArray(b []byte) (t [][]byte, rem []byte, err error) {
rem = b
var openBracket bool
// Pre-allocate slice with estimated capacity to reduce reallocations
// Estimate based on typical array sizes (can grow if needed)
t = make([][]byte, 0, 16)
for ; len(rem) > 0; rem = rem[1:] {
if rem[0] == '[' {
openBracket = true