c++arraysperformance

How to fast initialize with 1 really big array


I have enermous array:

int* arr = new int[BIGNUMBER];

How to fullfil it with 1 number really fast. Normally I would do

for(int i = 0; i < BIGNUMBER; i++)
    arr[i] = 1

but I think it would take long.

Can I use memcpy or similar?


Solution

  • You could try using the standard function std::uninitialized_fill_n:

    #include <memory>
    
    // ...
    
    std::uninitialized_fill_n(arr, BIGNUMBER, 1);
    

    In any case, when it comes to performance, the rule is to always make measurements to back up your assumptions - especially if you are going to abandon a clear, simple design to embrace a more complex one because of an alleged performance improvement.

    EDIT:

    Notice that - as Benjamin Lindley mentioned in the comments - for trivial types std::uninitialized_fill_n does not bring any advantage over the more obvious std::fill_n. The advantage would exist for non-trivial types, since std::uninitialized_fill would allow you to allocate a memory region and then construct objects in place.

    However, one should not fall into the trap of calling std::uninitialized_fill_n for a memory region that is not uninitialized. The following, for instance, would give undefined behavior:

    my_object* v = new my_object[BIGNUMBER];
    std::uninitialized_fill_n(my_object, BIGNUMBER, my_object(42)); // UB!