helpers: Avoid url.Parse in RelURL and AbsURL if we can - hugo - [fork] hugo port for 9front
HTML git clone git@git.drkhsh.at/hugo.git
DIR Log
DIR Files
DIR Refs
DIR Submodules
DIR README
DIR LICENSE
---
DIR commit ed7e250068a495469a0f8e0859c7f667330b1013
DIR parent 6a09e7f28e0d779aed504379e8eb486c9da9040a
HTML Author: Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Date: Mon, 12 Jun 2023 15:08:40 +0200
helpers: Avoid url.Parse in RelURL and AbsURL if we can
```
RelURL-10 159ns ± 5% 18ns ± 4% -88.89% (p=0.029 n=4+4)
AbsURL/relurl-10 532ns ± 0% 537ns ± 0% +1.09% (p=0.029 n=4+4)
AbsURL/absurl-10 142ns ± 0% 4ns ± 3% -96.91% (p=0.029 n=4+4)
name old alloc/op new alloc/op delta
RelURL-10 144B ± 0% 0B -100.00% (p=0.029 n=4+4)
AbsURL/relurl-10 544B ± 0% 544B ± 0% ~ (all equal)
AbsURL/absurl-10 144B ± 0% 0B -100.00% (p=0.029 n=4+4)
name old allocs/op new allocs/op delta
RelURL-10 1.00 ± 0% 0.00 -100.00% (p=0.029 n=4+4)
AbsURL/relurl-10 10.0 ± 0% 10.0 ± 0% ~ (all equal)
AbsURL/absurl-10 1.00 ± 0% 0.00 -100.00% (p=0.029 n=4+4)
```
Diffstat:
M helpers/url.go | 26 ++++++++++++++++++--------
1 file changed, 18 insertions(+), 8 deletions(-)
---
DIR diff --git a/helpers/url.go b/helpers/url.go
@@ -98,12 +98,11 @@ func (p *PathSpec) URLEscape(uri string) string {
// AbsURL creates an absolute URL from the relative path given and the BaseURL set in config.
func (p *PathSpec) AbsURL(in string, addLanguage bool) string {
- url, err := url.Parse(in)
+ isAbs, err := p.IsAbsURL(in)
if err != nil {
return in
}
-
- if url.IsAbs() || strings.HasPrefix(in, "//") {
+ if isAbs || strings.HasPrefix(in, "//") {
// It is already absolute, return it as is.
return in
}
@@ -149,16 +148,27 @@ func (p *PathSpec) getBaseURLRoot(path string) string {
}
}
-func (p *PathSpec) RelURL(in string, addLanguage bool) string {
- baseURL := p.getBaseURLRoot(in)
- canonifyURLs := p.Cfg.CanonifyURLs()
+func (p *PathSpec) IsAbsURL(in string) (bool, error) {
+ // Fast path.
+ if strings.HasPrefix(in, "http://") || strings.HasPrefix(in, "https://") {
+ return true, nil
+ }
+ u, err := url.Parse(in)
+ if err != nil {
+ return false, err
+ }
+ return u.IsAbs(), nil
+}
- url, err := url.Parse(in)
+func (p *PathSpec) RelURL(in string, addLanguage bool) string {
+ isAbs, err := p.IsAbsURL(in)
if err != nil {
return in
}
+ baseURL := p.getBaseURLRoot(in)
+ canonifyURLs := p.Cfg.CanonifyURLs()
- if (!strings.HasPrefix(in, baseURL) && url.IsAbs()) || strings.HasPrefix(in, "//") {
+ if (!strings.HasPrefix(in, baseURL) && isAbs) || strings.HasPrefix(in, "//") {
return in
}