Skip to content
Open
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-08-01 - Chained String Replace
**Learning:** Using 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` for string manipulation functions called frequently on hot paths to minimize allocations and improve performance.
31 changes: 25 additions & 6 deletions src/main/kotlin/html4tree/main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,31 @@ fun go(topDir: String, maxLevel: Int) {
}

fun String.escapeHtml(): String {
return this.replace("&", "&")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#x27;")
.replace("`", "&#x60;")
// ⚡ Bolt: Use a single-pass loop with a lazily-initialized StringBuilder
// to avoid intermediate string allocations from chained replace calls.
var sb: java.lang.StringBuilder? = null
for (i in this.indices) {
val c = this[i]
val replacement = when (c) {
'&' -> "&amp;"
'<' -> "&lt;"
'>' -> "&gt;"
'"' -> "&quot;"
'\'' -> "&#x27;"
'`' -> "&#x60;"
else -> null
}
if (replacement != null) {
if (sb == null) {
sb = java.lang.StringBuilder(this.length + 16)
sb.append(this, 0, i)
}
sb.append(replacement)
} else {
sb?.append(c)
}
}
return sb?.toString() ?: this
}

fun String.urlEncodePath(): String {
Expand Down
Loading