What is faster - accessing elements of a multiarray using element selection operator, or traversing over the multiarray using iterators?
In my case, I need to do a full pass over all elements of multiarray each time.
What is faster - accessing elements of a multiarray using element selection operator, or traversing over the multiarray using iterators?
In my case, I need to do a full pass over all elements of multiarray each time.
The fastest way to access every element of a
boost::multi_array
is viadata()
andnum_elements()
.With
data()
you gain access to the underlying raw storage (a contiguous block that contains the array‘s data) so there isn't need for multiple index calculations (consider also thatmulti_array
can index arrays from bases different from 0 and this is a further complication).A simple test gives:
By default boost access methods perform range checking. If a supplied index is out of the range defined for an array, an assertion will abort the program. To disable range checking, you can define the
BOOST_DISABLE_ASSERTS
preprocessor macro prior to includingmulti_array.hpp
in your application.This will reduce a lot the performance difference:
Performance difference increases (i.e.
data()
is faster):Anyway this kind of optimization is unlikely to make a measurable difference in a real program. You shouldn't worry about this unless you've conclusively determined, through extensive testing, that it is the source of some sort of bottleneck.
Source: