Skip to content

Commit e9e48b2

Browse files
isopovqingyang-hu
andauthored
GODRIVER-2542 optimize objectid hex func (#1062)
Co-authored-by: Qingyang Hu <[email protected]>
1 parent 60e3958 commit e9e48b2

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

bson/primitive/objectid.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ func (id ObjectID) Timestamp() time.Time {
6161

6262
// Hex returns the hex encoding of the ObjectID as a string.
6363
func (id ObjectID) Hex() string {
64-
return hex.EncodeToString(id[:])
64+
var buf [24]byte
65+
hex.Encode(buf[:], id[:])
66+
return string(buf[:])
6567
}
6668

6769
func (id ObjectID) String() string {

bson/primitive/objectid_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ func TestString(t *testing.T) {
2828
require.Contains(t, id.String(), id.Hex())
2929
}
3030

31+
func BenchmarkHex(b *testing.B) {
32+
id := NewObjectID()
33+
for i := 0; i < b.N; i++ {
34+
id.Hex()
35+
}
36+
}
37+
3138
func TestFromHex_RoundTrip(t *testing.T) {
3239
before := NewObjectID()
3340
after, err := ObjectIDFromHex(before.Hex())

0 commit comments

Comments
 (0)