Search code examples
carraysruntimezerofill

Runtime of Initializing an Array Zero-Filled


If I were to define the following array using the zero-fill initialization syntax on the stack:

int arr[ 10 ] = { 0 };

... is the run time constant or linear?

My assumption is that it's a linear run time -- my assumption is only targeting the fact that calloc must go over every byte to zero-fill it.

If you could also provide a why and not just it's order xxx that would be tremendous!


Solution

  • The runtime is linear in the array size.

    To see why, here's a sample implementation of memset, which initializes an array to an arbitrary value. At the assembly-language level, this is no different than what goes on in your code.

    void *memset(void *dst, int val, size_t count) {
        unsigned char *start = dst;
        for (size_t i = 0; i < count; i++)
            *start++ = value;
        return dst;
    }
    

    Of course, compilers will often use intrinsics to set multiple array elements at a time. Depending on the size of the array and things like alignment and padding, this might make the runtime over array length more like a staircase, with the step size based on the vector length. Over small differences in array size, this would effectively make the runtime constant, but the general pattern is still linear.