Skip to content

Commit 71ae9b4

Browse files
committed
hugolib: Rewrite replaceDivider to reduce memory allocation
```bash name old time/op new time/op delta ReplaceDivider-4 9.76µs ±105% 7.96µs ±24% ~ (p=0.690 n=5+5) name old alloc/op new alloc/op delta ReplaceDivider-4 3.46kB ± 0% 1.54kB ± 0% -55.56% (p=0.008 n=5+5) name old allocs/op new allocs/op delta ReplaceDivider-4 6.00 ± 0% 1.00 ± 0% -83.33% (p=0.008 n=5+5) ```
1 parent 199816f commit 71ae9b4

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

‎hugolib/page.go‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"errors"
1919
"fmt"
2020
"reflect"
21+
"unicode"
2122

2223
"github.com/bep/gitmap"
2324

@@ -488,17 +489,23 @@ var (
488489
// whether the contentis truncated or not.
489490
// Note: The content slice will be modified if needed.
490491
func replaceDivider(content, from, to []byte) ([]byte, bool) {
491-
sections := bytes.Split(content, from)
492+
dividerIdx := bytes.Index(content, from)
493+
if dividerIdx == -1 {
494+
return content, false
495+
}
496+
497+
afterSummary := content[dividerIdx+len(from):]
492498

493499
// If the raw content has nothing but whitespace after the summary
494500
// marker then the page shouldn't be marked as truncated. This check
495501
// is simplest against the raw content because different markup engines
496502
// (rst and asciidoc in particular) add div and p elements after the
497503
// summary marker.
498-
truncated := (len(sections) == 2 &&
499-
len(bytes.Trim(sections[1], " \n\r")) > 0)
504+
truncated := bytes.IndexFunc(afterSummary, func(r rune) bool { return !unicode.IsSpace(r) }) != -1
505+
506+
content = append(content[:dividerIdx], append(to, afterSummary...)...)
500507

501-
return bytes.Join(sections, to), truncated
508+
return content, truncated
502509

503510
}
504511

‎hugolib/page_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1107,7 +1107,7 @@ func TestReplaceDivider(t *testing.T) {
11071107
expectedTruncated bool
11081108
}{
11091109
{"none", "a", "b", "none", false},
1110-
{"summary divider content", "divider", "HUGO", "summary HUGO content", true},
1110+
{"summary <!--more--> content", "<!--more-->", "HUGO", "summary HUGO content", true},
11111111
{"summary\n\ndivider", "divider", "HUGO", "summary\n\nHUGO", false},
11121112
{"summary\n\ndivider\n\r", "divider", "HUGO", "summary\n\nHUGO\n\r", false},
11131113
}

0 commit comments

Comments
 (0)