How does the way MATLAB passes parameters to function - by values vs by objects - affect the perfomance?
Show older comments
I have three functions that run exactly the same calculation, but there is difference in time consumption. This whole code is a simplification of a much complicated and longer code, and the use of class is necessary in that code. This is just for testing purpose.
function [] = maincalc3 ()
inputvar=inputclass();
to1end = 0;
to2end = 0;
to3end = 0;
j = 100;
for i = 1:j;
t1=tic;
[out] = func1 (inputvar);
to1end=toc(t1) + to1end;
t2=tic;
[out2] = func2 (inputvar.s);
to2end=toc(t2) + to2end;
t3=tic;
[out3] = func3 (inputvar);
to3end=toc(t3) + to3end;
end
The class inputclass:
classdef inputclass
properties
s = 1;
end
end
func1():
function f = func1 (inputvar)
f = inputvar.s;
end
func2():
function f = func2 (s)
f = s;
end
func3():
function [f] = func3 (inputvar)
s=inputvar.s;
f = s;
end
and the result:
to1end =
0.002419525505078
to2end =
0.001517134538850
to3end =
0.002353777529397
func1() and func3() take about the same time, but func2() take about 60% less time. Can someone explain why this is happening?
Answers (1)
Sean de Wolski
on 2 Aug 2013
Edited: Sean de Wolski
on 2 Aug 2013
0 votes
My guess is that because you are passing in two variables that are not classes, the JIT is better able to optimize it. It also only requires passing the reference to the variable and not the whole class, not sure if this impacts performance or not.
It's important to point out that 100 calculations are still taking a few thousandths of a second for essentially a no-operation calculation. Are you going to be calling this millions of times? Is it going to be a no-op calculation? The reason I ask is related to Doug's most recent video:
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!