# Performance issue due to function as an argument

**URL:** <https://discourse.julialang.org/t/performance-issue-due-to-function-as-an-argument/104093>\
**Category:** General Usage\
**Tags:** question, performance\
**Created:** [September 21, 2023, 5:49am UTC](https://discourse.julialang.org/t/performance-issue-due-to-function-as-an-argument/104093 "2023-09-21T05:49:36Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![Chong\_Wang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chong_wang/32/20307_2.png) [@Chong\_Wang](https://discourse.julialang.org/u/Chong_Wang)\
**Post date:** [September 21, 2023, 5:49am UTC](https://discourse.julialang.org/t/performance-issue-due-to-function-as-an-argument/104093/1 "2023-09-21T05:49:36Z")

</div>

```julia
using LinearAlgebra, InteractiveUtils, BenchmarkTools

function process_matrix(f, matrix, vectors)
    N, M, L = size(matrix)
    #coefficients = map(f, vectors)
    #coefficients = [ones(Float64, 4, 4) * norm(v) for v in vectors]
    ret = zeros(ComplexF64, L, L)
    for i in 1:L, j in 1:L
        for k in 1:N
            for a in 1:M, b in 1:M
                ret[i, j] = coefficients[k][a, b] * matrix[k, a, i] * matrix[k, b, j]
            end
        end
    end

    return ret
end

function _f(v)
    return ones(Float64, 4, 4) * norm(v)
end

N = 6000
M = 4
L = 12
vectors = [rand(2) for _ in 1:N]
matrix = rand(ComplexF64, N, M, L)

@btime process_matrix(_f, matrix, vectors)

```

With this script, I get `3.014 s (81778660 allocations: 2.04 GiB)` if I uncomment the first comment (defining `coefficients`) and `22.304 ms (12003 allocations: 2.25 MiB)` if I uncomment the second comment.

It seems the two definitions of `coefficients` should be the same, and both versions do not show type instability from `@code_warntype`. What is causing the huge performance difference?

---

_[View the full topic](https://discourse.julialang.org/t/performance-issue-due-to-function-as-an-argument/104093)._
