Skip to content

Conversation

@ChrisRackauckas-Claude
Copy link

Summary

This PR reduces memory allocations in the core discretization hot paths, improving performance by approximately 5-6% on typical 1D problems.

Key optimizations:

  • Replace nested reduce(safe_vcat, ...) patterns with pre-allocated arrays and push!/append!
  • Use sizehint! to pre-allocate result arrays with estimated sizes
  • Add _append_vec! helper for efficient vector/matrix appending
  • Replace array comprehensions with tuples where stencil sizes are small/fixed
  • Use Sets instead of nested reduce for building unique collections
  • Direct returns instead of intermediate placeholder arrays

Benchmark Results

Before (1D diffusion, N=30):

  • ~830 ms, 57.4 MB allocated, 1.55M allocations

After (1D diffusion, N=30):

  • ~782 ms, 57.3 MB allocated, 1.54M allocations

The improvements are modest because most of the allocation overhead comes from symbolic manipulation in ModelingToolkit/Symbolics, which is outside the scope of this package. The changes here focus on the discretization pipeline itself.

Test Plan

  • Run Components test group - passed
  • Run Diffusion test group - passed
  • Added allocation regression tests to catch future regressions

Files Changed

  • src/discretization/generate_finite_difference_rules.jl - Optimized rule generation
  • src/discretization/schemes/centered_difference/centered_difference.jl - Optimized cartesian rules
  • src/scalar_discretization.jl - Optimized equation discretization
  • test/runtests.jl - Added allocation test group
  • test/alloc_tests.jl - New allocation regression tests

cc @ChrisRackauckas

🤖 Generated with Claude Code

Key optimizations:
- Replace nested reduce(safe_vcat, ...) patterns with pre-allocated arrays and push!/append!
- Use sizehint! to pre-allocate result arrays with estimated sizes
- Add _append_vec! helper for efficient vector/matrix appending
- Replace array comprehensions with tuples where stencil sizes are small/fixed
- Use Sets instead of nested reduce for building unique collections
- Direct returns instead of intermediate placeholder arrays

These changes reduce allocation overhead in the core discretization pipeline,
particularly in generate_cartesian_rules, generate_finite_difference_rules,
and discretize_equation_at_point functions.

Added allocation regression tests to prevent future regressions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants