Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@
## 2024-05-24 - Loop Allocation Hot Paths
**Learning:** Rendering directory entries with repeated string concatenation and list-based exclusion lookups creates avoidable allocation and lookup cost in large directories.
**Action:** Use `StringBuilder` for entry rendering and a `Set` for excluded file names.

## 2024-07-25 - Avoid Chained String Replacements
**Learning:** In Kotlin, using multiple chained `.replace()` calls on a String for frequent operations (like HTML escaping) is inefficient due to multiple intermediate allocations.
**Action:** Use a single-pass loop with a lazily-initialized `StringBuilder` to prevent intermediate string allocations, significantly improving performance on hot paths.
32 changes: 26 additions & 6 deletions src/main/kotlin/html4tree/main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,33 @@ fun go(topDir: String, maxLevel: Int) {
}
}

// ⚡ Bolt Optimization: Replace chained .replace() with single-pass StringBuilder
// Reduces intermediate allocations and improves performance when escaping strings.
fun String.escapeHtml(): String {
return this.replace("&", "&")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#x27;")
.replace("`", "&#x60;")
var sb: StringBuilder? = null
for (i in this.indices) {
val char = this[i]
val replacement = when (char) {
'&' -> "&amp;"
'<' -> "&lt;"
'>' -> "&gt;"
'"' -> "&quot;"
'\'' -> "&#x27;"
'`' -> "&#x60;"
else -> null
}

if (replacement != null) {
if (sb == null) {
sb = StringBuilder(this.length + 16)
sb.append(this, 0, i)
}
sb.append(replacement)
} else {
sb?.append(char)
}
}
return sb?.toString() ?: this
}

fun String.urlEncodePath(): String {
Expand Down
2 changes: 2 additions & 0 deletions src/test/kotlin/html4tree/MainTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ class MainTest {
assertEquals("&#x60;", "`".escapeHtml())
assertEquals("&amp;&lt;&gt;&quot;&#x27;&#x60;", "&<>\"'`".escapeHtml())
assertEquals("normal text", "normal text".escapeHtml())
assertEquals("a&amp;b", "a&b".escapeHtml())
assertEquals("hello &amp; world", "hello & world".escapeHtml())
}

@Test
Expand Down
Loading