From ddfb261f5778d71162db070aeef21830f9ad9ac9 Mon Sep 17 00:00:00 2001 From: seonghobae <8172694+seonghobae@users.noreply.github.com> Date: Fri, 21 Aug 2026 04:13:44 +0000 Subject: [PATCH] Optimize max row calculation using vapply instead of sapply Replaced `sapply` with `vapply(..., numeric(1))` in `llcont.lavaan` when calculating the maximum number of rows in `mispatts`. This avoids the overhead of return type deduction and simplification in interpreted code, improving performance and strictly enforcing type safety. --- .jules/bolt.md | 3 +++ R/llcont.R | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.jules/bolt.md b/.jules/bolt.md index f658475..1e89448 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -15,3 +15,6 @@ ## 2024-05-15 - [R Performance: ifelse Overhead] **Learning:** In R, ifelse evaluates both true and false branches entirely before subsetting, which is very inefficient for vector operations. **Action:** Optimize this by preallocating with res <- Y * 0 to preserve attributes and using vectorized subsetting like if any cond res subset <- ... +## 2026-08-11 - Safe type deduction using vapply +**Learning:** In R codebases, using `sapply` over a list involves significant overhead to deduce and simplify the return type in interpreted code. +**Action:** When the return type and length are known, always prefer `vapply(..., FUN.VALUE = type)` over `sapply(...)` for better performance and strict type safety. diff --git a/R/llcont.R b/R/llcont.R index d8e496a..16d948a 100644 --- a/R/llcont.R +++ b/R/llcont.R @@ -407,7 +407,8 @@ llcont.lavaan <- function(x, ...){ if(tolower(lavInspect(x, "options")$missing) == "ml.x") stop("cannot handle lavaan models with missing='ml.x'. consider using missing='ml'.", call. = FALSE) mispatts <- lavInspect(x, "patterns") if(any(class(mispatts) == "list")){ - npatts <- max(sapply(mispatts, nrow)) + ## Bolt: replaced sapply(...) with optimized vapply(...) for performance and safety + npatts <- max(vapply(mispatts, nrow, numeric(1))) } else { npatts <- nrow(mispatts) }