Skip to content

Commit

Permalink
helpers: Avoid url.Parse in RelURL and AbsURL if we can
Browse files Browse the repository at this point in the history
```
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)
```
  • Loading branch information
bep committed Jun 12, 2023
1 parent 6a09e7f commit ed7e250
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions helpers/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}

Expand Down

0 comments on commit ed7e250

Please sign in to comment.