Using subrange makes array operations slow
Show older comments
This is a question about the performance of code which I would naively expect to be much better. I define two random arrays:
a = randn(1, 10000);
b = randn(10000, 1);
Then try to multiply them together in two ways:
timeit(@() a*b)
ans =
4.3080e-06
timeit(@() a(1:10000)*b(1:10000))
ans =
1.5634e-05
You can see that when I use a sub-range of the arrays, multiplication gets about 3.6x slower, even in the case when the subrange is the whole array.
I could imagine that there is some overhead in parsing the subrange part of the command; but when the vectors become longer, the "overhead" grows:
a = randn(1, 1000000);
b = randn(1000000, 1);
timeit(@() a*b)
ans =
0.0010
timeit(@() a(1:1000000)*b(1:1000000))
ans =
0.0062
So, I have the two-fold question:
1) As a matter of curiosity, why is the performance so much worse when I use sub-ranges?
2) When we wish to perform read-only operations on sub-ranges, what can we do (besides copying the array) to keep performance reasonable?
Thanks, Clayton
PS. Version information: MATLAB Version: 8.3.0.532 (R2014a) Operating System: Microsoft Windows 7 Ultimate Version 6.1 (Build 7601: Service Pack 1) Java Version: Java 1.7.0_11-b21 with Oracle Corporation Java HotSpot™ 64-Bit Server VM mixed mode
Accepted Answer
More Answers (0)
Categories
Find more on Performance and Memory in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!