Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,12 @@ fun SubjectTrendLineChart(
val dashedLines = mutableMapOf<String, List<Triple<Triple<Int, Double, String>, Triple<Int, Double, String>, Color>>>()

groupedSubjects.forEach { (baseName, keys) ->
val allPoints = mutableListOf<Triple<Int, Double, String>>()
keys.forEach { key ->
subjectPoints[key]?.forEachIndexed { index, score ->
if (score != null) {
allPoints.add(Triple(index, score, key))
}
}
// Optimization: Replace manual mutable list initialization and nested iteration
// with a single flatMap step to improve parsing performance and reduce memory allocations
val allPoints = keys.flatMap { key ->
subjectPoints[key]?.mapIndexedNotNull { index, score ->
if (score != null) Triple(index, score, key) else null
} ?: emptyList()
}
Comment on lines +116 to 122

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The PR description states that this change reduces memory allocations and improves performance. However, using flatMap combined with mapIndexedNotNull actually increases memory allocations and GC pressure.

For every key in keys, mapIndexedNotNull allocates a new temporary ArrayList. Then flatMap allocates another ArrayList and copies the elements over. In contrast, the original code allocated exactly one MutableList per baseName and appended elements directly to it.

To keep the code clean, idiomatic, and highly performant without intermediate list allocations, we can use Kotlin's buildList builder function.

Suggested change
// Optimization: Replace manual mutable list initialization and nested iteration
// with a single flatMap step to improve parsing performance and reduce memory allocations
val allPoints = keys.flatMap { key ->
subjectPoints[key]?.mapIndexedNotNull { index, score ->
if (score != null) Triple(index, score, key) else null
} ?: emptyList()
}
val allPoints = buildList {
keys.forEach { key ->
subjectPoints[key]?.forEachIndexed { index, score ->
if (score != null) {
add(Triple(index, score, key))
}
}
}
}

allPointsMap[baseName] = allPoints

Expand Down
Loading