executing-plans
executing-plans
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available
optimize-shiny-performanceprofvis、bindCache、memoise、async/promises、debounce/throttle、および 長時間実行される計算向けのExtendedTaskを使ってShinyアプリケーションのパフォーマンスを プロファイルして最適化します。ユーザーインタラクション中にアプリが遅くまたは 応答しないと感じるとき、同時負荷でサーバーリソースが枯渇するとき、特定の操作が ボトルネックを生じさせるとき、または多くの同時ユーザーを持つ本番デプロイメント用に アプリを準備するときに使用します。
Independent GitHub snapshot · Automated classification · Original documentation governs
キャッシング、非同期操作、リアクティブグラフの最適化を通じてShinyアプリケーションのパフォーマンスをプロファイルし、診断し、最適化します。
# Profile with profvis
profvis::profvis({
shiny::runApp("path/to/app", display.mode = "normal")
})
# Or profile specific operations
profvis::profvis({
result <- expensive_computation(data)
})
主要なボトルネックを特定します:
リアクティブグラフ分析にリアクティブログを使用します:
# Enable reactive logging
options(shiny.reactlog = TRUE)
shiny::runApp("path/to/app")
# Press Ctrl+F3 in the browser to view the reactive graph
期待結果: 2〜3の最大のボトルネックが明確に特定されます。
失敗時: profvisが有用な詳細を表示しない場合は、特定のセクションをprofvis::profvis()でラップしてください。reactlogが圧倒的な場合は、一度に1つのインタラクションに集中してください。
不要なリアクティブの無効化を減らします:
# BAD: Recomputes on ANY input change
output$plot <- renderPlot({
data <- load_data() # Runs every time
filtered <- data[data$category == input$category, ]
plot(filtered)
})
# GOOD: Isolate data loading from filtering
raw_data <- reactive({
load_data()
}) |> bindCache() # Cache the expensive part
filtered_data <- reactive({
raw_data()[raw_data()$category == input$category, ]
})
output$plot <- renderPlot({
plot(filtered_data())
})
不要な無効化を防ぐためにisolate()を使用します:
# Only recompute when the button is clicked, not on every input change
output$result <- renderText({
input$compute # Take dependency on button
isolate({
paste("N =", input$n, "Mean =", mean(rnorm(input$n)))
})
})
高頻度の入力にはdebounce()とthrottle()を使用します:
# Debounce text input — wait 500ms after user stops typing
search_text <- reactive(input$search) |> debounce(500)
# Throttle slider — update at most every 250ms
slider_value <- reactive(input$slider) |> throttle(250)
期待結果: リアクティブグラフが必要な再計算のみを発火します。
失敗時: 依存関係を削除すると機能が壊れる場合は、暗黙的なリアクティブ依存関係に頼る代わりにreq()を使って明示的なガードを追加してください。
output$plot <- renderPlot({
create_expensive_plot(filtered_data())
}) |> bindCache(input$category, input$date_range)
output$table <- renderDT({
expensive_query(input$filters)
}) |> bindCache(input$filters)
bindCacheは入力値をキャッシュキーとして使用します。同じ入力が再び発生すると、キャッシュされた結果がすぐに返されます。
# Cache expensive function results
load_reference_data <- memoise::memoise(
function(dataset_name) {
readr::read_csv(paste0("data/", dataset_name, ".csv"))
},
cache = cachem::cache_disk("cache/", max_age = 3600)
)
# In global.R or outside server function — computed once at app startup
reference_data <- readr::read_csv("data/reference.csv")
model <- readRDS("models/trained_model.rds")
server <- function(input, output, session) {
# reference_data and model are available to all sessions
# without reloading
}
期待結果: 繰り返しの操作がキャッシュされた結果を使用し、応答時間が大幅に短縮されます。
失敗時: キャッシュが大きくなりすぎる場合はmax_ageまたはmax_sizeの制限を設定してください。キャッシュされた値が古い場合はmax_ageを減らすかキャッシュクリアボタンを追加してください。bindCacheがエラーを引き起こす場合は、キャッシュキーの入力がシリアライズ可能であることを確認してください。
長時間実行される計算にはExtendedTask(Shiny >= 1.8.1)を使用します:
server <- function(input, output, session) {
# Define the extended task
analysis_task <- ExtendedTask$new(function(data, params) {
promises::future_promise({
# This runs in a background process
run_heavy_analysis(data, params)
})
}) |> bind_task_button("run_analysis")
# Trigger the task
observeEvent(input$run_analysis, {
analysis_task$invoke(dataset(), input$params)
})
# Use the result
output$result <- renderTable({
analysis_task$result()
})
}
Shiny < 1.8.1のアプリにはpromisesを直接使用します:
library(promises)
library(future)
plan(multisession, workers = 4)
server <- function(input, output, session) {
result <- eventReactive(input$compute, {
future_promise({
Sys.sleep(5) # Simulate long computation
expensive_analysis(isolate(input$params))
})
})
output$table <- renderTable({
result()
})
}
期待結果: 長時間操作がUIをブロックしない。計算実行中に他のユーザーがインタラクションできます。
失敗時: future_promiseがエラーになる場合はplan(multisession)が設定されているか確認してください。futureで変数が利用できない場合は明示的に渡してください — futureは別のRプロセスで実行されます。
レンダリングのオーバーヘッドを削減します:
# Use plotly for interactive plots instead of re-rendering
output$plot <- plotly::renderPlotly({
plotly::plot_ly(filtered_data(), x = ~x, y = ~y, type = "scatter")
})
# Use server-side DT for large tables
output$table <- DT::renderDataTable({
DT::datatable(large_data(), server = TRUE, options = list(
pageLength = 25,
processing = TRUE
))
})
# Conditional UI to avoid rendering hidden elements
output$details <- renderUI({
req(input$show_details)
expensive_details_ui()
})
期待結果: レンダリング操作が高速化され、UIをブロックしません。
失敗時: plotlyが大きなデータセットで遅い場合は、WebGLレンダリングにtoWebGL()を使用するか、プロット前にデータをダウンサンプリングしてください。
# Before/after benchmarking
system.time({
shiny::testServer(myModuleServer, args = list(...), {
session$setInputs(category = "A")
session$flushReact()
})
})
# Load testing with shinyloadtest
shinyloadtest::record_session("http://localhost:3838")
shinyloadtest::shinycannon(
"recording.log",
"http://localhost:3838",
workers = 10,
loaded_duration_minutes = 5
)
shinyloadtest::shinyloadtest_report("recording.log")
期待結果: 応答時間および/または同時ユーザー容量の測定可能な改善。
失敗時: パフォーマンスが改善されなかった場合は、次のボトルネックを見つけるために再プロファイルしてください。パフォーマンス最適化は反復的です — まず最大のボトルネックを修正し、次に再測定してください。
bindCache()に欠けている依存関係を追加してください。future_promiseは別のプロセスで実行されます。グローバル変数、データベース接続、リアクティブな値は明示的にキャプチャする必要があります。build-shiny-module — 保守可能なリアクティブコードのためのモジュラーアーキテクチャscaffold-shiny-app — 最初から適切なアプリフレームワークを選択するdeploy-shiny-app — 適切なサーバーリソースで最適化されたアプリをデプロイするtest-shiny-app — パフォーマンスリグレッションテスト