Skip to content

Commit c861080

Browse files
committed
Make RowsAffected faster
The current implementation uses two loops, first one to find out where digits start and second one to loop over the digits. The modified implementation starts at the end and loops till digits end. It is a bit faster than baseline.
1 parent fe8740a commit c861080

1 file changed

Lines changed: 8 additions & 13 deletions

File tree

pgconn/pgconn.go

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -777,25 +777,20 @@ func NewCommandTag(s string) CommandTag {
777777
// RowsAffected returns the number of rows affected. If the CommandTag was not
778778
// for a row affecting command (e.g. "CREATE TABLE") then it returns 0.
779779
func (ct CommandTag) RowsAffected() int64 {
780-
// Find last non-digit
781-
idx := -1
780+
// Parse the number from the end in a single pass.
781+
var n int64
782+
var mult int64 = 1
783+
782784
for i := len(ct.s) - 1; i >= 0; i-- {
783-
if ct.s[i] >= '0' && ct.s[i] <= '9' {
784-
idx = i
785+
c := ct.s[i]
786+
if c >= '0' && c <= '9' {
787+
n += int64(c-'0') * mult
788+
mult *= 10
785789
} else {
786790
break
787791
}
788792
}
789793

790-
if idx == -1 {
791-
return 0
792-
}
793-
794-
var n int64
795-
for _, b := range ct.s[idx:] {
796-
n = n*10 + int64(b-'0')
797-
}
798-
799794
return n
800795
}
801796

0 commit comments

Comments
 (0)