Saturday, 17 January 2015

C++11 Features - std::array

std::array has the memory footprint of c-style array, but with std::vector's interface. Like the c-style array and unlike std::vector, std::arrary allocates the objects on the stack. The underline objects exists within the object of std::array. The motivation behind std::array I think has at least 3 significant benifits,
    - Save the memory comparing with std::vector
    - Provide STL interface
    - Performance optimization
        * Memory allocated on stack as c-style array
        * No memory fragment as on stack
        * No performance penalty of dynamic malloc/free lock between threads

1. std::array vs. c-style array
The major difference between might be that std::array provides STL interface. One of worthing mentioning is the pair of rbegin()/rend() to reversely traverse the array.

Except this difference std::array takes all the advantage and disadvantage of c-style array.
Advantages like:
    - Memory allocated on stack
    - No performance penalty from memory fragment, and locking and multi-threading application

Disadvantage (of c-style array):
    - The typename it takes should not have polymophisim
        * std::array<Base, 3> myBaseArr = {Derived(), Base(), Derived()};
        * Compilation errors and object slicing
    - The typename should be POD type
        * Data type provides default constructor
        * Or initialized with initializer-list with user-defined constructor
    - Worse syntax than c-style of array in multiple dimensional array
        * int threeDimArr[5][6][7]
        * std::array<std::array<std::array<int, 7>, 6>, 5> threeDimStdArr;

2. std::array vs. std::vector
The key difference between std::array and std::vector is that the underline objects on std::array is with the object of std::array, however on std::array is dynamic allocated on the heap. The potential performance issues are the memory fragment and the malloc/free lock between threads. (The threads have separated stacks but may or may not have separated heaps. It depends on OS. Unix and Windows share the heap between threads and Symbian doesn't.)

Another important difference is the memory size it takes. std::array is no greater than std::vector. std::array works only when the size of the container is known in advance however std::vector can be expanding as the size grows. The potential memory reallocation causes performance penalty and invalidates all the iterators. In order to reduce performance impact normally std::vector allocates more memory than it actually needs. However std::array won't have this issue, because its usage will be only limited to the scenarios that the size is knowing in advance.

So in order to have out-of-scope life, std::array objects have to be created on the heap. However std::vector objects on the stack can be easily moved around with const complexity to have out-of-scope life in C++11. Because the underline objects are allocated on heap in std::vector. The operations like std::move and std::swap takes const complexity, if the typename objects support std::swap and std::move operation.. However std::array will take linear complexity to do these two operations no matter what typename objects are, which are just as expensive as std::copy.

3. User cases
I have not seen many legitimate user cases that replaces c-style array with std::array, because I can't see many obvious benefits. I can see one case,
    - Need to use algorithm in the reverse order. For instance traverse reversely.

However I can definitely see one case that replace std::vector with std::array, when the size of std::vector is known in advance and the object is an automatic variable and is not returned. Benefits like,
    - Keep the same interface for algorithms
    - Less memory used
    - Performance gain from no memory fragment and malloc/free locking between threads

Performance gain could be an especially true case if the containers are used in performance hot spot.

4. Performance on Microsoft Visual Studio Express 2013
As I discussed the performance issue of std::vector and did comparison between it and c-style array. Please see C++ Performance - Array vs. std::vector. I am curious about how the performance of std::array will be as it have nearly identical interface as std::vector but the same memory footprint as c-style array.

This is the implementation of std::array::operator[] in  Visual Studio
// ********************************************************************************
reference operator[](size_type _Pos)
{ // subscript mutable sequence
 #if _ITERATOR_DEBUG_LEVEL == 2
if (_Size <= _Pos)
_DEBUG_ERROR("array subscript out of range");

 #elif _ITERATOR_DEBUG_LEVEL == 1
_SCL_SECURE_VALIDATE_RANGE(_Pos < _Size);
 #endif /* _ITERATOR_DEBUG_LEVEL */

_Analysis_assume_(_Pos < _Size);

return (_Elems[_Pos]);
}

const_reference operator[](size_type _Pos) const
{ // subscript nonmutable sequence
 #if _ITERATOR_DEBUG_LEVEL == 2
if (_Size <= _Pos)
_DEBUG_ERROR("array subscript out of range");

 #elif _ITERATOR_DEBUG_LEVEL == 1
_SCL_SECURE_VALIDATE_RANGE(_Pos < _Size);
 #endif /* _ITERATOR_DEBUG_LEVEL */

_Analysis_assume_(_Pos < _Size);

return (_Elems[_Pos]);
}

// ********************************************************************************

The implementation shows that std::array as a standard container in Visual Studio has the all the sanity checking of accessing the data as the rest. It have two levels of debugging level setting. Based on the investigation of C++ Performance - Array vs. std::vector, I believe that std::array should have the similar performance as std::vector without considering the performance penalty caused by memory allocation/free and locking from heap and stack.

Really look forward to seeing some performance optimization implemented by compiler. So in a word for some performance hot spot c-style array is still the winner.

Bibliography:
[1] Scotts Meyer, "Effective Mordern C++", O'REILLY, 2014 First Release
[2] Bjarne Stroustrup, "The C++ Programming Language", C++11, 4th Edition
[3] C++ Reading Club @ IG Group

2 comments:

  1. But Dr. Itua, Traditional Herbal Practitioner in Africa, Have cured for HIV which is extracted from some rare herbals. It is highly potential to cure AIDS 100% without any residue. Dr Itua herbal medicine has already passed various blogs on how he use his powerful herbals to heal all kind of diseases such as. Herpes, HIV, Diabetes, Hepatitis, Epilepsy, also his herbal boost immune system as well. I'm telling this because he uses his herbal medicine to cure me from hepatitis B and HIV, which i have being living for 9 months now with no side effect. The Herbal Medicine is just as good when drinking it although i have to use rest room after drinking it which I do not really care about because i just want to get the virus out of my body, I will recommend Dr Itua to anyone sick out here to contact Dr Itua with this following information.
    Email...drituaherbalcenter@gmail.com
    Whatsapp Or Call...+2348149277967.
    He might be late to respond because he always busy with patent, but he will surely get back to you with positive response.

    ReplyDelete
  2. I’m Mark Russ , I contracted HIV in 2009, I was told by my doctor that
    there’s no possible cure for HIV. I started taking my ARV’s, My CD4 was 77
    and viral load was 112,450. I saw a website of Dr. Imoloa also I saw a lot
    of testimonials about him on how he uses herbal medicine to cure HIV. I
    contacted him and told him my problems, He sent me the herbal medicine and
    I took it for 7 days after then I went for check-up and I was cured. The
    medicine has NO SIDE EFFECT, there’s no special diet when taking the
    medicine. He also cure DIABETES, EX BACK, ALS, HEPATITIS B, CANCER, HERPES
    1) If you want your ex back.
    (2) If you always have bad dreams.
    (3) You want to be promoted in your
    office.
    (4) You want women/men to run after
    you.
    (5) If you want your own children
    (6) You want to be rich.
    (7) You want to tie your husband/wife to
    be
    yours forever.
    (8) If you need financial assistance.
    (9) How you been scammed and you
    (10) and if you ant your herpes cure back
    want to recover you lost money
    (11) CANCER,
    (12) DIABETES,
    (13) HIV&AIdS,
    (14) URINARY TRACT INFECTION,
    (15) CANCER,
    (16) IMPOTENCE,
    (17) BARENESS/INFERTILIY
    (18) DIARRHEA
    (19) ASTHMA..
    Also contact him with the above.
    and lots more. You can reach him on drimoloaherbalmademedicine@gmail.com or
    Whatsapp +2347081986098 all thanks to dr imoloa he is really a great man .

    ReplyDelete