# Non-allocating matrix inversion

**URL:** <https://discourse.julialang.org/t/non-allocating-matrix-inversion/62264>\
**Category:** Performance\
**Tags:** matrices\
**Created:** [June 2, 2021, 11:48am UTC](https://discourse.julialang.org/t/non-allocating-matrix-inversion/62264 "2021-06-02T11:48:48Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![gustaphe](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gustaphe/32/18174_2.png) [@gustaphe](https://discourse.julialang.org/u/gustaphe)\
**Post date:** [June 2, 2021, 1:56pm UTC](https://discourse.julialang.org/t/non-allocating-matrix-inversion/62264/8 "2021-06-02T13:56:48Z")

</div>

```julia
using LinearAlgebra, BenchmarkTools, BenchmarkPlots, StatsPlots
bg = BenchmarkGroup()
bg[:inv] = @benchmarkable A*inv(B)*b setup=(A=rand(100,100);B=rand(100,100);b=rand(100))
bg[:backslash] = @benchmarkable A*(B\b) setup=(A=rand(100,100);B=rand(100,100);b=rand(100))
bg[:slash] = @benchmarkable (A/B)*b setup=(A=rand(100,100);B=rand(100,100);b=rand(100))
bg[:qr] = @benchmarkable A*(qr(B)\b) setup=(A=rand(100,100);B=rand(100,100);b=rand(100))
bg[:lu] = @benchmarkable A*(lu(B)\b) setup=(A=rand(100,100);B=rand(100,100);b=rand(100))
bg[:inv_pre] = @benchmarkable A*Q*b setup=(A=rand(100,100);B=rand(100,100);Q=inv(B);b=rand(100))
bg[:qr_pre] = @benchmarkable A*(Q\b) setup=(A=rand(100,100);B=rand(100,100);Q=qr(B);b=rand(100))
bg[:lu_pre] = @benchmarkable A*(Q\b) setup=(A=rand(100,100);B=rand(100,100);Q=lu(B);b=rand(100))
trial = run(bg)
plot(trial; yscale=:log10)

```

![image](https://global.discourse-cdn.com/julialang/original/3X/7/f/7f1c3cf13385d2244e930209a06315d324597692.png)

Even ignoring the numerical instability of the inversion process, you can see that `A*(B\b)` is faster than inversion, and that `qr(B)` is faster when used as a precomputed auxiliary.

Edit: Added in `LU` decomposition, because it’s the preferred algorithm.

---

_[View the full topic](https://discourse.julialang.org/t/non-allocating-matrix-inversion/62264)._
