From 99b4f0ce74ea4f5f5f05233ad6ee2abad5e46b3a Mon Sep 17 00:00:00 2001 From: jvoisin Date: Sat, 7 Dec 2024 23:36:10 +0100 Subject: [PATCH] Simplify hasRequiredAttributes This function takes around 1.5% of the total CPU time on my instance, and most of it is spent in `mapassign_faststr` to initialize the `map`. This is replaced with a switch-case construct, that should be both significantly faster as well as pretty dull in term of memory consumption. --- internal/reader/sanitizer/sanitizer.go | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/internal/reader/sanitizer/sanitizer.go b/internal/reader/sanitizer/sanitizer.go index 05c6e7b8246..20adef9d77e 100644 --- a/internal/reader/sanitizer/sanitizer.go +++ b/internal/reader/sanitizer/sanitizer.go @@ -294,24 +294,16 @@ func isPixelTracker(tagName string, attributes []html.Attribute) bool { } func hasRequiredAttributes(tagName string, attributes []string) bool { - elements := map[string][]string{ - "a": {"href"}, - "iframe": {"src"}, - "img": {"src"}, - "source": {"src", "srcset"}, - } - - if attrs, ok := elements[tagName]; ok { - for _, attribute := range attributes { - if slices.Contains(attrs, attribute) { - return true - } - } - - return false + switch tagName { + case "a": + return slices.Contains(attributes, "href") + case "iframe", "img": + return slices.Contains(attributes, "src") + case "source": + return slices.Contains(attributes, "src") || slices.Contains(attributes, "srcset") + default: + return true } - - return true } // See https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml