A simple demonstration to show the effect of preallocation in MATLAB
Recently, I was asked by a friend “why do your MATLAB codes contains a preallocation line for matrices?… Isn’t it easy to just do things in place and let MATLAB understand what the initialisation of the matrix should be.” “Well, it would work; but, have you ever thought about how would it affect the computation speeed (in a way, the overall code running efficiency)”, I said.
So, to address the above question, I wanted to demonstrate it visually using a small MATLAB code that has both preallocation and non-preallocation routines. The problem is simple. Show the effect of preallocation on continous array appends and updates. If you are comfortable in looking at the code, here is it:
The method 1 is without preallocation, and method 2 is with preallocation. The preallocation in method 2 is nothing but start with an empty matrix and keep appending a random numbered array to it. See the speed difference yourself.
Now, you may be thinking, so what? It is just a matter of few seconds. Well, I want to share with some numbers:
A program that I wrote without preallocation took roughly 18Hr in a machine with 64GB memory, and 16-core Intel Xeon CPU. And, the exact same program with preallocation finished the execution in 5Min in the same machine. Convinced?
Let me know, if this post helped you. Also, you may be interested in going through the official page of Mathworks on Preallocation. Cheers!