Просмотр исходного кода

refactor(sanitizer): 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.
Julien Voisin 1 год назад
Родитель
Сommit
331c831c23
1 измененных файлов с 9 добавлено и 17 удалено
  1. 9 17
      internal/reader/sanitizer/sanitizer.go

+ 9 - 17
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