]> Sergey Matveev's repositories - btrtrc.git/commitdiff
PieceStateRuns: reduce copying and make inlineable
authorYenForYang <YenForYang@users.noreply.github.com>
Wed, 1 Sep 2021 04:06:25 +0000 (23:06 -0500)
committerMatt Joiner <anacrolix@gmail.com>
Wed, 1 Sep 2021 04:51:45 +0000 (14:51 +1000)
Just a heads up: using `range` and/or `defer` prevents function inlining. This is fine for infrequently called functions and/or large functions, but for simple public methods like these, I'd assume it's better for them to be inlined.

t.go

diff --git a/t.go b/t.go
index a593a6bbf9a0c669945e111514860e9d89f4f857..69cef55410a391ab9e1bbfb546a859ee90fe785e 100644 (file)
--- a/t.go
+++ b/t.go
@@ -44,20 +44,26 @@ func (t *Torrent) NewReader() Reader {
 
 type PieceStateRuns []PieceStateRun
 
-func (me PieceStateRuns) String() string {
-       ss := make([]string, 0, len(me))
-       for _, psr := range me {
-               ss = append(ss, psr.String())
+func (me PieceStateRuns) String() (s string) {
+       if len(me) > 0 {
+               var sb strings.Builder
+               sb.WriteString(me[0].String())
+               for i := 1; i < len(me); i += 1 {
+                       sb.WriteByte(' ')
+                       sb.WriteString(me[i].String())
+               }
+               return sb.String()
        }
-       return strings.Join(ss, " ")
+       return
 }
 
 // Returns the state of pieces of the torrent. They are grouped into runs of same state. The sum of
 // the state run-lengths is the number of pieces in the torrent.
-func (t *Torrent) PieceStateRuns() PieceStateRuns {
+func (t *Torrent) PieceStateRuns() (runs PieceStateRuns) {
        t.cl.rLock()
-       defer t.cl.rUnlock()
-       return t.pieceStateRuns()
+       runs = t.pieceStateRuns()
+       t.cl.rUnlock()
+       return
 }
 
 func (t *Torrent) PieceState(piece pieceIndex) PieceState {