Performance Awareness
Preallocate Vector
Fill Known Size
When the output size is known, preparing the vector shape before filling it keeps intent clear.
Program
Play the script to change the planned length and watch the filled total update.
preallocate_vector.R
item_count <-
result <- numeric(item_count)
result <- seq_len(item_count) * 2
total <- sum(result)
label <- paste("sum", total, sep = ":")
cat(label, "\n", sep = "")
item_count <-
result <- numeric(item_count)
result <- seq_len(item_count) * 2
total <- sum(result)
label <- paste("sum", total, sep = ":")
cat(label, "\n", sep = "")
item_count <-
result <- numeric(item_count)
result <- seq_len(item_count) * 2
total <- sum(result)
label <- paste("sum", total, sep = ":")
cat(label, "\n", sep = "")
known size
The selected count defines the output length before values are filled.
preallocation
`numeric(item_count)` creates a vector of the intended size.
filled vector
Replacing the zeros with computed values models a predictable fill step.