I have a long running function in MATLAB that I tried to speed up by adding caching and wound up slowing down my performance significantly. My code is basically searching for continuous "horizontal" lines in an edge detected image and the original code looks something like this:
function lineLength = getLineLength(img, startRow, startCol)
[nRows, nCols] = size(img);
lineLength = 0;
if startRow < 1 || startRow > nRows
return;
end
for curCol = startCol:nCols
if img(curCol)
lineLength = lineLength + 1;
continue;
elseif lineLength > 0
lengths = zeros(2,1);
lengths(1) = getLineLength(img, startRow - 1, curCol);
lengths(2) = getLineLength(img, startRow + 1, curCol);
increment = max(lengths);
lineLength = lineLength + increment;
end
break; %// At this point the end of the current line has been reached
end
end function
Since performance in this function is not what I would like, I thought I would add caching of the length from any point something like the following:
function lineLength = getLineLength(img, startRow, startCol)
persistent pointCache;
if startRow == 0 && startCol == 0
pointCache = zeros(size(img, 1), size(img, 2), 2);
end
[nRows, nCols] = size(img);
lineLength = 0;
if startRow < 1 || startRow > nRows
return;
end
for curCol = startCol:nCols
if pointCache(startRow, curCol, 2)
lineLength = lineLength + pointCache(startRow, curCol, 1);
break;
end
if img(curCol)
lineLength = lineLength + 1;
continue;
elseif lineLength > 0
lengths = zeros(2,1);
lengths(1) = getLineLength(img, startRow - 1, curCol);
lengths(2) = getLineLength(img, startRow + 1, curCol);
increment = max(lengths);
lineLength = lineLength + increment;
end
break; %// At this point the end of the current line has been reached
end
pointCache(startRow, startCol, 1) = lineLength;
pointCache(startRow, startCol, 2) = 1;
end function
What surprised me is that implementing this caching actually made my performance worse, rather than better. My best guesses are that either the global
variable is getting me in trouble, or its the extra memory use, but I don't have enough MATLAB experience to know.
Edited...
As Gautam correctly pointed out that there was a bug in the original code that was ignoring the results of the recursion. This is what the actual code does. I'm sure it's obvious, but MATLAB is not my native language so if there's a more MATLABy way to do this, I'd love the suggestions.