How does the way MATLAB passes parameters to function - by values vs by objects - affect the perfomance?

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?

Antworten (1)

Sean de Wolski
Sean de Wolski am 2 Aug. 2013
Bearbeitet: Sean de Wolski am 2 Aug. 2013
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:

1 Kommentar

Good video, but the code I posted is just for testing purpose. I have a much longer code that consists about 20 sub functions (probably 3000 lines of code in total), and it'll be called hundreds of thousand of times, if not millions. So I need to know how the three approaches could affect the performance.
And I just edited the code that I posted, the functions will only pass one variable, not two.
One more thing, what do you mean the variable is not class?

Melden Sie sich an, um zu kommentieren.

Kategorien

Gefragt:

am 2 Aug. 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by