Understanding memory usage in Julia

that very much helped! Thanks a lot :slight_smile:

1 Like

I would like to add that as of now, Dec. 2025, I seem to be running to the same issue. I too am working on a FEM solver in Julia and during a loop where a large sparse stiffness matrix is updated, memory keeps on rising. Calling explicitly GC.gc() at the end of the loop fixed the issue, but this should not be needed. For reference, here is the code for the loop

# Boundary conditions
RHS::Vector{Float64} = BoundaryIntegral(mesh, Hext, shell_id)

# Reset the permeability
mu .= mu0

# FEM
u::Vector{Float64} = zeros(mesh.nv+1)
  
Hfield::Matrix{Float64} = zeros(3, mesh.nt)
H::Vector{Float64} = zeros(mesh.nt)
Hold::Vector{Float64} = zeros(mesh.nt)

att::Int32 = 0
div::Float64 = Inf
while div > picardDeviation && att < maxAtt 

    att += 1
    Hold .= H

    # Updated the compressed stiffness matrix
    n = 0
    for i in 1:4
        for j in 1:4
            n += 1
            for k in 1:mesh.nt
                Acsc[(n-1)*mesh.nt + k] = Ak[n, k] * mu[k]
            end
        end
    end # Acsc

    # Update the global stiffness matrix
    A = sparse(rowIDs, colIDs, Acsc, mesh.nv, mesh.nv)

    # Magnetic scalar potential
    u = [A Lag;Lag' 0]\[-RHS;0]
    
    # Check solution
    if any(x -> !isfinite(x), u)
        error("Nans/Infs in the scalar potential")
    end

    # Magnetic field
    Hfield .= 0.0
    for k in 1:mesh.nt
        nds = mesh.t[:,k];

        # Sum the contributions
        for nd in nds
            # obtain the element parameters
            _, b, c, d = abcd(mesh.p,nds,nd)

            Hfield[1, k] -= u[nd]*b;
            Hfield[2, k] -= u[nd]*c;
            Hfield[3, k] -= u[nd]*d;
        end
    end

    # Magnetic field intensity
    for k in 1:mesh.nt
        H[k] = norm(Hfield[:, k])
    end

    # Update magnetic permeability            
    mu[mesh.InsideElements] .= spl(H[mesh.InsideElements])

    # Check deviation from previous result
    div = mu0*maximum(abs.(H[mesh.InsideElements].-Hold[mesh.InsideElements]))
    verbose ? println(att, " | mu0 |H(n)-H(n-1)| = ", div) : nothing

    # Ask for garbage collection because otherwise there is a memory build up
    # Still don't know why
    GC.gc()

end # Picard Iteration

Which Julia version?

Version 1.12.2 , happens both on Windows and Linux (Ubuntu 24.04)
I also created a comment on this github issue, and seems to be getting some traction. https://github.com/JuliaLang/julia/issues/50658#issuecomment-3647135647

2 Likes