protocol: optimize ConnectionID.String (#5351)

This function is used by qlog, so it should be fast.
This commit is contained in:
Marten Seemann
2025-10-03 14:27:39 +08:00
committed by GitHub
parent ce7c9ea883
commit f607ef489f
2 changed files with 12 additions and 3 deletions

View File

@@ -2,8 +2,8 @@ package protocol
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
)
@@ -26,7 +26,7 @@ func (c ArbitraryLenConnectionID) String() string {
if c.Len() == 0 {
return "(empty)"
}
return fmt.Sprintf("%x", c.Bytes())
return hex.EncodeToString(c.Bytes())
}
const maxConnectionIDLen = 20
@@ -100,7 +100,7 @@ func (c ConnectionID) String() string {
if c.Len() == 0 {
return "(empty)"
}
return fmt.Sprintf("%x", c.Bytes())
return hex.EncodeToString(c.Bytes())
}
type DefaultConnectionIDGenerator struct {

View File

@@ -68,6 +68,15 @@ func TestConnectionIDZeroValue(t *testing.T) {
require.Equal(t, "(empty)", (ConnectionID{}).String())
}
// The string representation of a connection ID is used in qlog, so it should be fast.
func BenchmarkConnectionIDStringer(b *testing.B) {
c := ParseConnectionID([]byte{0xde, 0xad, 0xbe, 0xef, 0x42})
b.ReportAllocs()
for b.Loop() {
_ = c.String()
}
}
func TestArbitraryLenConnectionID(t *testing.T) {
b := make([]byte, 42)
rand.Read(b)