
489Memory-Related Techniques
% Bad idea: allocates 8 MB double array, then converts to 1MB int8 array
data = int8(zeros(1000,1000)); % 1M elements
⇨ Elapsed time is 0.000113 seconds.
% Better: directly allocate the array as a 1MB int8 array - faster
data = zeros(1000,1000,'int8');
⇨ Elapsed time is 0.000072 seconds.
For example, int8(ones(1000,1)) rst allocates 8000 bytes for 1000 double-precision val-
ues, then allocates a separate 1000-bytes block for the converted data.* This is not only
wasteful in CPU cycles and memory, but could also cause severe slowdowns when the
data is large, possibly even thrashing and out-of-memory errors. In ...