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)
```
This commit is contained in:
Bjørn Erik Pedersen 2023-06-12 15:08:40 +02:00
parent 6a09e7f28e
commit ed7e250068

View file

@ -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
}