Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zero a new array?

Tags:

c++

1:

int a[100] = {};

2:

int a[100];
memset(a, 0, sizeof(a));

3:

int a[100];
fill(a, a + 100, 0);

What is the best way to zero a new array from the methods shown above and what is the difference between them?

like image 659
Gaith Avatar asked Oct 19 '25 13:10

Gaith


2 Answers

1: The best. It sets all the values to their default value which for most is 0.

2: This is dangerous, it copies the pattern 0 through the whole array. For example if the array is of floats, there is no guarantee that it is represented as zeros. Also memset copies byte wise NOT word wise which can cause all sorts of issues if you pass it something other than zero. For example memset(a, 1, ...) will cause it to be filled with 16843009. Memset should not be used unless you are using C-strings.

3: Legal, and legible. Easy to extend to non-zero values while (1) will not. Although more verbose.

like image 178
Cramer Avatar answered Oct 21 '25 03:10

Cramer


Decided to investigate the performance question using VS2010, full optimization.

Interesting result:

1: 13105

2: 13044

3: 4546

No initialization case: 906.

So it looks highly like VS2010 uses memset for case 1, but that fill is better optimized.

#include "stdafx.h"
#include <Windows.h>
#include <algorithm>
#include <iostream>

int  fref()
{
    int a[1024];
    return a[512] - a[256];
}

int f1()
{
    int a[1024] = {};

    return a[512] - a[256];
}

int  f2()
{
    int a[1024];
    memset(a, 0, sizeof(a));
    return a[512] - a[256];
}



int f3()
{
    int a[1024];
    std::fill(a, a + 100, 0);
    return a[512] - a[256];
}

typedef int (*Function)();

LONGLONG time(Function function)
{
    const unsigned numLoops = 50000;
    LARGE_INTEGER start;
    QueryPerformanceCounter(&start);
    for(unsigned j = 1; j != numLoops; ++j)
    function();
    LARGE_INTEGER end;
    QueryPerformanceCounter(&end);
    return end.QuadPart-start.QuadPart;
}

Function tests[]= 
{
    &fref, &f1, &f2, &f3
};

const unsigned numTests = sizeof(tests)/sizeof(tests[0]);

LONGLONG results[numTests] = {};


int _tmain(int argc, _TCHAR* argv[])
{
    for(unsigned i = 0; i != numTests; ++i)
    {
        results[i] = time(tests[i]);
    }
    for(unsigned i = 0; i != numTests; ++i)
        std::cout << results[i] << std::endl;
    getchar();
    return 0;
}
like image 39
Keith Avatar answered Oct 21 '25 04:10

Keith