In order to refactor my MATLAB code, I thought I'd pass around functions as arguments (what MATLAB calls anonymous functions), inspired by functional programming.
However, it seems performance is hit quite severely. In the examples below, I compare different approaches. (The code snippet is wrapped in a function in order to be able to use subfunctions)
The result I get is 0 seconds for direct, almost 0 seconds using a subfunction, and 5 seconds using anonymous functions. I'm running MATLAB 7.7 (R2007b) on OS X 10.6, on a C2D 1.8 GHz.
Can anyone run the code and see what they get? I'm especially interested in performance on Windows.
function [] = speedtest()
clear all; close all;
function y = foo(x)
y = zeros(1,length(x));
for j=1:N
y(j) = x(j)^2;
end
end
x = linspace(-100,100,100000);
N = length(x);
%% direct
t = cputime;
y = zeros(1,N);
for i=1:N
y(i) = x(i)^2;
end
r1 = cputime - t;
%% using subfunction
t = cputime;
y = foo(x);
r2 = cputime - t;
%% using anon function
fn = @(x) x^2;
t = cputime;
y = zeros(1,N);
for i=1:N
y(i) = fn(x(i));
end
r3 = cputime-t;
[r1 r2 r3]
end