efficiency using struct.field vs variable

19 views (last 30 days)
Hi, I am curious about the efficiency of using structure.field vs variable in function but I don't know how to search such particular question.
Basically I need to use a variable inside a function so I use structure to pass the information. Then inside the function, the variable will be used multiple times. So I can have two approaches. Every time I need the variable, I can either assign it to a variable at the start of the function, or use it from the structure. Two approaches in code provided below:
Method 1:
Method 2:
Not sure which one is faster if I got loads of use. Hope my question is clear.

Accepted Answer

Walter Roberson
Walter Roberson on 16 Nov 2017
In the small timing test I just did, leaving the value inside the struct was slightly faster. However, it is entirely possible that I simply did not do enough calculation with the variable to make up for the cost of doing the assignment to the variable.
Basically... you should time both versions.
Be careful, though: I have multiple times found that if I use something like
result1 = timeit(first_test,0)
result2 = timeit(second_test,0)
that first test I do is notably slower, so exchanging first_test and second_test would give very different results about which was faster. It is not just the first timeit() call either: if I use a loop to call timeit repeatedly then the results for the entire first loop are odd.
str = struct('foo', rand(1,50), 'bar', 'hello there how are you?');
F1 = @() fun_direct_struct(str);
F2 = @() fun_tovar(str);
N = 100;
T1a = zeros(1, N);
T1b = zeros(1, N);
T2a = zeros(1, N);
for K = 1 : N
T1a(K) = timeit(F1, 0);
for K = 1 : N
T2a = timeit(F2, 0);
for K = 1 : N
T1b = timeit(F1, 0);
plot(1:N, T1a, 'k*-', 1:N, T1b, 'kv--', 1:N, T2a, 'b.:')
legend({'T1a', 'T1b', 'T2a'});
In the above, T1b and T2a are pretty much constant in the time they take each iteration, but T1a varies a lot, especially initially. If you were to only measure F1 the first time then you would get a very different impression about which function was slower.

Sign in to comment.

More Answers (0)


Find more on Loops and Conditional Statements 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!