C++ Vector appear to be faster than C Array (Time). Why ?

Hello I have seen that C++ Vector vs Array (Time).
On my mac the vector take times to be defined but after the comparison give vector for winner.
How it works ?
I was said int[] are faster than dynamic vector ?

#include <iostream>
#include <vector>
using namespace std;
#define N (100000000)
//int sd[N];
int main() {
    clock_t start;
    double temps;
    static int sd[N];
    start = clock();
    for (unsigned long i=0 ; i < N ; i++){
        if(sd[i]==3)
            ;
    }
    temps = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
    printf("Time: %f ms\n",temps);
    vector<int>vd(N);
    start = clock();
    for (unsigned long i=0 ; i < N ; i++){
        if(vd[i]==3)
            ;
    }
    temps = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
    printf("Time: %f ms\n",temps);
    while (1)
        ;
    return 0;
}

I have those results :

  • How do i avoid running out of memory when performing a task on every item of core data?
  • Freeing iOS UIWebView resources after usage
  • IOS Segue - Terminating app due to uncaught exception 'NSGeneric Exception'
  • XCode can't find symbols for a specific iOS library/framework project
  • iOS Memory Warnings
  • EXC_BAD_ACCESS (code=1, address=0x0) when stepping in debugger
    • Time: 422.87400 ms
    • Time: 300.84700 ms
      Even if it begining with vector, vector appear to be faster than c array.

    Thank You for your explaination.

    Another question : in xcode, why i see memory used by declation vector and for static c array I have to go all the memory cells as in the code (for … if(sd[i]…)

    Thank You for your explaination.

    Solutions Collect From Internet About “C++ Vector appear to be faster than C Array (Time). Why ?”

    I have remarqued that if i initialize all the c array cells at 0 (for example or 6…) the c array will be faster or equal vector.

    int main() {
        clock_t start;
        double temps;
        static int sd[N];
        for (unsigned long i=0 ; i < N ; i++){
            sd[i]=0;
        }
    
        start = clock();
        //puts("initialized");
        for (unsigned long i=0 ; i < N ; i++){
            if(sd[i]==3)
                ;
        }
        temps = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
        printf("Time: %f ms\n",temps);
        //puts("initialized");
        vector<int>vd(N);
        start = clock();
        for (unsigned long i=0 ; i < N ; i++){
            if(vd[i]==3)
                ;
        }
        temps = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
        printf("Time: %f ms\n",temps);
    
        while (1)
            ;
        return 0;
    }
    

    And I will see the memory used in xcode with the initialization at 0 of all cells c array.

    So another question , why it is more rapid when you initialize in this case (or in general) ?