Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consider preallocating for speed [duplicate]

I was doing the following

for i = 1:m,
    index = 0;
    for j = 1:n,
        index = index+values(i,j)*2^(j-1);
        if (j==1)
            symbol_chip = chip_values(index+1,:);
        else
            symbol_chip = [symbol_chip chip_values(index+1,:)];
        end
    end
end

it tells me the following:

symbol_chip might be growing inside the loop. Consider preallocating for speed.

Any ideas?

like image 238
kl. Avatar asked Jan 28 '10 01:01

kl.


2 Answers

Yes. Each time you go around, your elseif block is resizing symbol_chip, which is expensive. Instead, rewrite your code so that you have (say) symbol_chip = zeros(max_size, 1); before the loop. Then, change the contents but not the size of symbol_chip.

You'll need to slightly change your approach, but it will be much faster if you do. If you're not annoyed by the current speed, don't change anything!

like image 103
Peter Avatar answered Nov 20 '22 13:11

Peter


M-Lint will throw this warning if you have a variable that grows inside a loop without being preallocated. You can remove this error by pre-allocating the collection variable.

For instance, if you knew that the variable symbol_chip would have at most i*j elements, you could preallocate it with the statement:

symbol_chip = zeros(i*j);

However, for most applications preallocation will only have a negligible effect on algorithm performance. I would only worry about it if you are dealing with very large data sets.

like image 2
BillyRayCyrus Avatar answered Nov 20 '22 12:11

BillyRayCyrus