Performance gap between vector and array Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Is std::vector so much slower than plain arrays?Why aren't variable-length arrays part of the C++ standard?Using arrays or std::vectors in C++, what's the performance gap?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?Improve INSERT-per-second performance of SQLite?What is the difference between call and apply?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?Why is it faster to process a sorted array than an unsorted array?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations

Amount of permutations on an NxNxN Rubik's Cube

How come Sam didn't become Lord of Horn Hill?

Can a new player join a group only when a new campaign starts?

If Windows 7 doesn't support WSL, then what does Linux subsystem option mean?

Why aren't air breathing engines used as small first stages?

Should I use a zero-interest credit card for a large one-time purchase?

Project Euler #1 in C++

Hangman Game with C++

Effects on objects due to a brief relocation of massive amounts of mass

How do living politicians protect their readily obtainable signatures from misuse?

How do I find out the mythology and history of my Fortress?

When a candle burns, why does the top of wick glow if bottom of flame is hottest?

What is this clumpy 20-30cm high yellow-flowered plant?

Multiple OR (||) Conditions in If Statement

A term for a woman complaining about things/begging in a cute/childish way

Most bit efficient text communication method?

How often does castling occur in grandmaster games?

Localisation of Category

Why wasn't DOSKEY integrated with COMMAND.COM?

Converted a Scalar function to a TVF function for parallel execution-Still running in Serial mode

The code below, is it ill-formed NDR or is it well formed?

Should I follow up with an employee I believe overracted to a mistake I made?

Why is my ESD wriststrap failing with nitrile gloves on?

Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?



Performance gap between vector and array



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Is std::vector so much slower than plain arrays?Why aren't variable-length arrays part of the C++ standard?Using arrays or std::vectors in C++, what's the performance gap?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?Improve INSERT-per-second performance of SQLite?What is the difference between call and apply?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?Why is it faster to process a sorted array than an unsorted array?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








16















I was trying to solve a coding problem in C++ which counts the number of prime numbers less than a non-negative number n.



So I first came up with some code:



int countPrimes(int n) 
vector<bool> flag(n+1,1);
for(int i =2;i<n;i++)

if(flag[i]==1)
for(long j=i;i*j<n;j++)
flag[i*j]=0;

int result=0;
for(int i =2;i<n;i++)
result+=flag[i];
return result;



which takes 88 ms and uses 8.6 MB of memory. Then I changed my code into:



int countPrimes(int n) 
// vector<bool> flag(n+1,1);
bool flag[n+1] ;
fill(flag,flag+n+1,true);
for(int i =2;i<n;i++)

if(flag[i]==1)
for(long j=i;i*j<n;j++)
flag[i*j]=0;

int result=0;
for(int i =2;i<n;i++)
result+=flag[i];
return result;



which takes 28 ms and 9.9 MB. I don't really understand why there is such a performance gap in both the running time and memory consumption. I have read relative questions like this one and that one but I am still confused.



EDIT: I reduced the running time to 40 ms with 11.5 MB of memory after replacing vector<bool> with vector<char>.










share|improve this question



















  • 6





    How are you compiling your code? What compiler options? Also; vector<bool> is special.

    – Jesper Juhl
    12 hours ago







  • 12





    be carfull, std::vector<bool> is a weird specialisation, more a bitset than a vector

    – Martin m
    11 hours ago






  • 2





    @Martinm @JesperJuhl Yes. I reduced the running time to 40 ms with 11.5 MB memory after replacing vector<bool> with vector<char>. Thank you.

    – Qin Heyang
    11 hours ago






  • 3





    you may gain some time changing one loop a bit: for(int i = 2; i * i <n;i++) since if i * i >= n then next loop does nothing.

    – Marek R
    11 hours ago







  • 3





    This doesn't address the question, but when you're dealing with boolean types, use true and false and not 1. So: vector<bool> flag(n+1, true); and if (flag[i]). That doesn't affect the result, but it makes it much clearer what you're doing.

    – Pete Becker
    10 hours ago

















16















I was trying to solve a coding problem in C++ which counts the number of prime numbers less than a non-negative number n.



So I first came up with some code:



int countPrimes(int n) 
vector<bool> flag(n+1,1);
for(int i =2;i<n;i++)

if(flag[i]==1)
for(long j=i;i*j<n;j++)
flag[i*j]=0;

int result=0;
for(int i =2;i<n;i++)
result+=flag[i];
return result;



which takes 88 ms and uses 8.6 MB of memory. Then I changed my code into:



int countPrimes(int n) 
// vector<bool> flag(n+1,1);
bool flag[n+1] ;
fill(flag,flag+n+1,true);
for(int i =2;i<n;i++)

if(flag[i]==1)
for(long j=i;i*j<n;j++)
flag[i*j]=0;

int result=0;
for(int i =2;i<n;i++)
result+=flag[i];
return result;



which takes 28 ms and 9.9 MB. I don't really understand why there is such a performance gap in both the running time and memory consumption. I have read relative questions like this one and that one but I am still confused.



EDIT: I reduced the running time to 40 ms with 11.5 MB of memory after replacing vector<bool> with vector<char>.










share|improve this question



















  • 6





    How are you compiling your code? What compiler options? Also; vector<bool> is special.

    – Jesper Juhl
    12 hours ago







  • 12





    be carfull, std::vector<bool> is a weird specialisation, more a bitset than a vector

    – Martin m
    11 hours ago






  • 2





    @Martinm @JesperJuhl Yes. I reduced the running time to 40 ms with 11.5 MB memory after replacing vector<bool> with vector<char>. Thank you.

    – Qin Heyang
    11 hours ago






  • 3





    you may gain some time changing one loop a bit: for(int i = 2; i * i <n;i++) since if i * i >= n then next loop does nothing.

    – Marek R
    11 hours ago







  • 3





    This doesn't address the question, but when you're dealing with boolean types, use true and false and not 1. So: vector<bool> flag(n+1, true); and if (flag[i]). That doesn't affect the result, but it makes it much clearer what you're doing.

    – Pete Becker
    10 hours ago













16












16








16








I was trying to solve a coding problem in C++ which counts the number of prime numbers less than a non-negative number n.



So I first came up with some code:



int countPrimes(int n) 
vector<bool> flag(n+1,1);
for(int i =2;i<n;i++)

if(flag[i]==1)
for(long j=i;i*j<n;j++)
flag[i*j]=0;

int result=0;
for(int i =2;i<n;i++)
result+=flag[i];
return result;



which takes 88 ms and uses 8.6 MB of memory. Then I changed my code into:



int countPrimes(int n) 
// vector<bool> flag(n+1,1);
bool flag[n+1] ;
fill(flag,flag+n+1,true);
for(int i =2;i<n;i++)

if(flag[i]==1)
for(long j=i;i*j<n;j++)
flag[i*j]=0;

int result=0;
for(int i =2;i<n;i++)
result+=flag[i];
return result;



which takes 28 ms and 9.9 MB. I don't really understand why there is such a performance gap in both the running time and memory consumption. I have read relative questions like this one and that one but I am still confused.



EDIT: I reduced the running time to 40 ms with 11.5 MB of memory after replacing vector<bool> with vector<char>.










share|improve this question
















I was trying to solve a coding problem in C++ which counts the number of prime numbers less than a non-negative number n.



So I first came up with some code:



int countPrimes(int n) 
vector<bool> flag(n+1,1);
for(int i =2;i<n;i++)

if(flag[i]==1)
for(long j=i;i*j<n;j++)
flag[i*j]=0;

int result=0;
for(int i =2;i<n;i++)
result+=flag[i];
return result;



which takes 88 ms and uses 8.6 MB of memory. Then I changed my code into:



int countPrimes(int n) 
// vector<bool> flag(n+1,1);
bool flag[n+1] ;
fill(flag,flag+n+1,true);
for(int i =2;i<n;i++)

if(flag[i]==1)
for(long j=i;i*j<n;j++)
flag[i*j]=0;

int result=0;
for(int i =2;i<n;i++)
result+=flag[i];
return result;



which takes 28 ms and 9.9 MB. I don't really understand why there is such a performance gap in both the running time and memory consumption. I have read relative questions like this one and that one but I am still confused.



EDIT: I reduced the running time to 40 ms with 11.5 MB of memory after replacing vector<bool> with vector<char>.







c++ arrays performance vector std






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 1 hour ago









isanae

2,55611437




2,55611437










asked 12 hours ago









Qin HeyangQin Heyang

30918




30918







  • 6





    How are you compiling your code? What compiler options? Also; vector<bool> is special.

    – Jesper Juhl
    12 hours ago







  • 12





    be carfull, std::vector<bool> is a weird specialisation, more a bitset than a vector

    – Martin m
    11 hours ago






  • 2





    @Martinm @JesperJuhl Yes. I reduced the running time to 40 ms with 11.5 MB memory after replacing vector<bool> with vector<char>. Thank you.

    – Qin Heyang
    11 hours ago






  • 3





    you may gain some time changing one loop a bit: for(int i = 2; i * i <n;i++) since if i * i >= n then next loop does nothing.

    – Marek R
    11 hours ago







  • 3





    This doesn't address the question, but when you're dealing with boolean types, use true and false and not 1. So: vector<bool> flag(n+1, true); and if (flag[i]). That doesn't affect the result, but it makes it much clearer what you're doing.

    – Pete Becker
    10 hours ago












  • 6





    How are you compiling your code? What compiler options? Also; vector<bool> is special.

    – Jesper Juhl
    12 hours ago







  • 12





    be carfull, std::vector<bool> is a weird specialisation, more a bitset than a vector

    – Martin m
    11 hours ago






  • 2





    @Martinm @JesperJuhl Yes. I reduced the running time to 40 ms with 11.5 MB memory after replacing vector<bool> with vector<char>. Thank you.

    – Qin Heyang
    11 hours ago






  • 3





    you may gain some time changing one loop a bit: for(int i = 2; i * i <n;i++) since if i * i >= n then next loop does nothing.

    – Marek R
    11 hours ago







  • 3





    This doesn't address the question, but when you're dealing with boolean types, use true and false and not 1. So: vector<bool> flag(n+1, true); and if (flag[i]). That doesn't affect the result, but it makes it much clearer what you're doing.

    – Pete Becker
    10 hours ago







6




6





How are you compiling your code? What compiler options? Also; vector<bool> is special.

– Jesper Juhl
12 hours ago






How are you compiling your code? What compiler options? Also; vector<bool> is special.

– Jesper Juhl
12 hours ago





12




12





be carfull, std::vector<bool> is a weird specialisation, more a bitset than a vector

– Martin m
11 hours ago





be carfull, std::vector<bool> is a weird specialisation, more a bitset than a vector

– Martin m
11 hours ago




2




2





@Martinm @JesperJuhl Yes. I reduced the running time to 40 ms with 11.5 MB memory after replacing vector<bool> with vector<char>. Thank you.

– Qin Heyang
11 hours ago





@Martinm @JesperJuhl Yes. I reduced the running time to 40 ms with 11.5 MB memory after replacing vector<bool> with vector<char>. Thank you.

– Qin Heyang
11 hours ago




3




3





you may gain some time changing one loop a bit: for(int i = 2; i * i <n;i++) since if i * i >= n then next loop does nothing.

– Marek R
11 hours ago






you may gain some time changing one loop a bit: for(int i = 2; i * i <n;i++) since if i * i >= n then next loop does nothing.

– Marek R
11 hours ago





3




3





This doesn't address the question, but when you're dealing with boolean types, use true and false and not 1. So: vector<bool> flag(n+1, true); and if (flag[i]). That doesn't affect the result, but it makes it much clearer what you're doing.

– Pete Becker
10 hours ago





This doesn't address the question, but when you're dealing with boolean types, use true and false and not 1. So: vector<bool> flag(n+1, true); and if (flag[i]). That doesn't affect the result, but it makes it much clearer what you're doing.

– Pete Becker
10 hours ago












3 Answers
3






active

oldest

votes


















18














std::vector<bool> isn't like any other vector. The documentation says:




std::vector<bool> is a possibly space-efficient specialization of
std::vector for the type bool.




That's why it may use up less memory than an array, because it might represent multiple boolean values with one byte, like a bitset. It also explains the performance difference, since accessing it isn't as simple anymore. According to the documentation, it doesn't even have to store it as a contiguous array.






share|improve this answer






























    13














    std::vector<bool> is special case. It is specialized template. Each value is stored in single bit, so bit operations are needed. This memory compact but has couple drawbacks (like no way to have a pointer to bool inside this container).



    Now bool flag[n+1]; compiler will usually allocate same memory in same manner as for char flag[n+1]; and it will do that on stack, not on heap.



    Now depending on page sizes, cache misses and i values one can be faster then other. It is hard to predict (for small n array will be faster, but for larger n result may change).



    As an interesting experiment you can change std::vector<bool> to std::vector<char>. In this case you will have similar memory mapping as in case of array, but it will be located at heap not a stack.






    share|improve this answer
































      2














      I'd like to add some remarks to the good answers already posted.




      • The performance differences between std::vector<bool> and std::vector<char> may vary (a lot) between different library implementations and different sizes of the vectors.



        See e.g. those quick benches: clang++ / libc++(LLVM) vs. g++ / libstdc++(GNU).



      • This: bool flag[n+1]; declares a Variable Length Array, which (despites some performance advantages due to it beeing allocated in the stack) has never been part of the C++ standard, even if provided as an extension by some (C99 compliant) compilers.


      • Another way to increase the performances could be to reduce the amount of calculations (and memory occupation) by considering only the odd numbers, given that all the primes except for 2 are odd.


      If you can bare the less readable code, you could try to profile the following snippet.



      int countPrimes(int n)

      if ( n < 2 )
      return 0;
      // Sieve starting from 3 up to n, the number of odd number between 3 and n are
      int sieve_size = n / 2 - 1;
      std::vector<char> sieve(sieve_size);
      int result = 1; // 2 is a prime.

      for (int i = 0; i < sieve_size; ++i)

      if ( sieve[i] == 0 )

      // It's a prime, no need to scan the vector again
      ++result;
      // Some ugly transformations are needed, here
      int prime = i * 2 + 3;
      for ( int j = prime * 3, k = prime * 2; j <= n; j += k)
      sieve[j / 2 - 1] = 1;



      return result;






      share|improve this answer

























      • Wow, 20 years after C99, and not even the most rudimentary VLAs... Looks like C++ is getting more and more behind C ;-) Afaik, there was once a proposal that would have made int array[length]; legal in C++, but even that proposal did not allow for multidimensional arrays, neither on the stack (int array2d[height][width]) nor on the heap (int (*array2d)[width] = new int[height][width];). Apparently, that proposal was never approved, even though C goes as far as to allow the multidimensional case (int (*array2d)[width] = malloc(height * sizeof(*array2d));) since 20 years ago...

        – cmaster
        7 hours ago











      • @cmaster Well, that's debatable ;)

        – Bob__
        7 hours ago











      • Yeah, I know. Especially since very few people actually understand the power of the C99 syntax - both of the top-scoring answers of the question you linked completely underestimate its value. Because, you see, C99 VLAs not just exist on the stack, they can also be allocated on the heap. I have already given an example of that, it's the last one. The real power comes from the fact that any C99 array type can have a runtime length, it can be pointed to or typedefed. And C99 does not care how many runtime length array types you nest, the indexing calculation comes out right.

        – cmaster
        3 hours ago











      • Long story short: I really enjoy working with C++ for the most part, but when it comes to manipulating multidimensional arrays of plain data, (images, volumes, simulations), I'll just fall back to C99 for its VLA syntax.

        – cmaster
        3 hours ago











      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55745312%2fperformance-gap-between-vectorbool-and-array%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      18














      std::vector<bool> isn't like any other vector. The documentation says:




      std::vector<bool> is a possibly space-efficient specialization of
      std::vector for the type bool.




      That's why it may use up less memory than an array, because it might represent multiple boolean values with one byte, like a bitset. It also explains the performance difference, since accessing it isn't as simple anymore. According to the documentation, it doesn't even have to store it as a contiguous array.






      share|improve this answer



























        18














        std::vector<bool> isn't like any other vector. The documentation says:




        std::vector<bool> is a possibly space-efficient specialization of
        std::vector for the type bool.




        That's why it may use up less memory than an array, because it might represent multiple boolean values with one byte, like a bitset. It also explains the performance difference, since accessing it isn't as simple anymore. According to the documentation, it doesn't even have to store it as a contiguous array.






        share|improve this answer

























          18












          18








          18







          std::vector<bool> isn't like any other vector. The documentation says:




          std::vector<bool> is a possibly space-efficient specialization of
          std::vector for the type bool.




          That's why it may use up less memory than an array, because it might represent multiple boolean values with one byte, like a bitset. It also explains the performance difference, since accessing it isn't as simple anymore. According to the documentation, it doesn't even have to store it as a contiguous array.






          share|improve this answer













          std::vector<bool> isn't like any other vector. The documentation says:




          std::vector<bool> is a possibly space-efficient specialization of
          std::vector for the type bool.




          That's why it may use up less memory than an array, because it might represent multiple boolean values with one byte, like a bitset. It also explains the performance difference, since accessing it isn't as simple anymore. According to the documentation, it doesn't even have to store it as a contiguous array.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 11 hours ago









          BlazeBlaze

          7,9691933




          7,9691933























              13














              std::vector<bool> is special case. It is specialized template. Each value is stored in single bit, so bit operations are needed. This memory compact but has couple drawbacks (like no way to have a pointer to bool inside this container).



              Now bool flag[n+1]; compiler will usually allocate same memory in same manner as for char flag[n+1]; and it will do that on stack, not on heap.



              Now depending on page sizes, cache misses and i values one can be faster then other. It is hard to predict (for small n array will be faster, but for larger n result may change).



              As an interesting experiment you can change std::vector<bool> to std::vector<char>. In this case you will have similar memory mapping as in case of array, but it will be located at heap not a stack.






              share|improve this answer





























                13














                std::vector<bool> is special case. It is specialized template. Each value is stored in single bit, so bit operations are needed. This memory compact but has couple drawbacks (like no way to have a pointer to bool inside this container).



                Now bool flag[n+1]; compiler will usually allocate same memory in same manner as for char flag[n+1]; and it will do that on stack, not on heap.



                Now depending on page sizes, cache misses and i values one can be faster then other. It is hard to predict (for small n array will be faster, but for larger n result may change).



                As an interesting experiment you can change std::vector<bool> to std::vector<char>. In this case you will have similar memory mapping as in case of array, but it will be located at heap not a stack.






                share|improve this answer



























                  13












                  13








                  13







                  std::vector<bool> is special case. It is specialized template. Each value is stored in single bit, so bit operations are needed. This memory compact but has couple drawbacks (like no way to have a pointer to bool inside this container).



                  Now bool flag[n+1]; compiler will usually allocate same memory in same manner as for char flag[n+1]; and it will do that on stack, not on heap.



                  Now depending on page sizes, cache misses and i values one can be faster then other. It is hard to predict (for small n array will be faster, but for larger n result may change).



                  As an interesting experiment you can change std::vector<bool> to std::vector<char>. In this case you will have similar memory mapping as in case of array, but it will be located at heap not a stack.






                  share|improve this answer















                  std::vector<bool> is special case. It is specialized template. Each value is stored in single bit, so bit operations are needed. This memory compact but has couple drawbacks (like no way to have a pointer to bool inside this container).



                  Now bool flag[n+1]; compiler will usually allocate same memory in same manner as for char flag[n+1]; and it will do that on stack, not on heap.



                  Now depending on page sizes, cache misses and i values one can be faster then other. It is hard to predict (for small n array will be faster, but for larger n result may change).



                  As an interesting experiment you can change std::vector<bool> to std::vector<char>. In this case you will have similar memory mapping as in case of array, but it will be located at heap not a stack.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 11 hours ago









                  Jesper Juhl

                  17.9k32647




                  17.9k32647










                  answered 11 hours ago









                  Marek RMarek R

                  13.8k22777




                  13.8k22777





















                      2














                      I'd like to add some remarks to the good answers already posted.




                      • The performance differences between std::vector<bool> and std::vector<char> may vary (a lot) between different library implementations and different sizes of the vectors.



                        See e.g. those quick benches: clang++ / libc++(LLVM) vs. g++ / libstdc++(GNU).



                      • This: bool flag[n+1]; declares a Variable Length Array, which (despites some performance advantages due to it beeing allocated in the stack) has never been part of the C++ standard, even if provided as an extension by some (C99 compliant) compilers.


                      • Another way to increase the performances could be to reduce the amount of calculations (and memory occupation) by considering only the odd numbers, given that all the primes except for 2 are odd.


                      If you can bare the less readable code, you could try to profile the following snippet.



                      int countPrimes(int n)

                      if ( n < 2 )
                      return 0;
                      // Sieve starting from 3 up to n, the number of odd number between 3 and n are
                      int sieve_size = n / 2 - 1;
                      std::vector<char> sieve(sieve_size);
                      int result = 1; // 2 is a prime.

                      for (int i = 0; i < sieve_size; ++i)

                      if ( sieve[i] == 0 )

                      // It's a prime, no need to scan the vector again
                      ++result;
                      // Some ugly transformations are needed, here
                      int prime = i * 2 + 3;
                      for ( int j = prime * 3, k = prime * 2; j <= n; j += k)
                      sieve[j / 2 - 1] = 1;



                      return result;






                      share|improve this answer

























                      • Wow, 20 years after C99, and not even the most rudimentary VLAs... Looks like C++ is getting more and more behind C ;-) Afaik, there was once a proposal that would have made int array[length]; legal in C++, but even that proposal did not allow for multidimensional arrays, neither on the stack (int array2d[height][width]) nor on the heap (int (*array2d)[width] = new int[height][width];). Apparently, that proposal was never approved, even though C goes as far as to allow the multidimensional case (int (*array2d)[width] = malloc(height * sizeof(*array2d));) since 20 years ago...

                        – cmaster
                        7 hours ago











                      • @cmaster Well, that's debatable ;)

                        – Bob__
                        7 hours ago











                      • Yeah, I know. Especially since very few people actually understand the power of the C99 syntax - both of the top-scoring answers of the question you linked completely underestimate its value. Because, you see, C99 VLAs not just exist on the stack, they can also be allocated on the heap. I have already given an example of that, it's the last one. The real power comes from the fact that any C99 array type can have a runtime length, it can be pointed to or typedefed. And C99 does not care how many runtime length array types you nest, the indexing calculation comes out right.

                        – cmaster
                        3 hours ago











                      • Long story short: I really enjoy working with C++ for the most part, but when it comes to manipulating multidimensional arrays of plain data, (images, volumes, simulations), I'll just fall back to C99 for its VLA syntax.

                        – cmaster
                        3 hours ago















                      2














                      I'd like to add some remarks to the good answers already posted.




                      • The performance differences between std::vector<bool> and std::vector<char> may vary (a lot) between different library implementations and different sizes of the vectors.



                        See e.g. those quick benches: clang++ / libc++(LLVM) vs. g++ / libstdc++(GNU).



                      • This: bool flag[n+1]; declares a Variable Length Array, which (despites some performance advantages due to it beeing allocated in the stack) has never been part of the C++ standard, even if provided as an extension by some (C99 compliant) compilers.


                      • Another way to increase the performances could be to reduce the amount of calculations (and memory occupation) by considering only the odd numbers, given that all the primes except for 2 are odd.


                      If you can bare the less readable code, you could try to profile the following snippet.



                      int countPrimes(int n)

                      if ( n < 2 )
                      return 0;
                      // Sieve starting from 3 up to n, the number of odd number between 3 and n are
                      int sieve_size = n / 2 - 1;
                      std::vector<char> sieve(sieve_size);
                      int result = 1; // 2 is a prime.

                      for (int i = 0; i < sieve_size; ++i)

                      if ( sieve[i] == 0 )

                      // It's a prime, no need to scan the vector again
                      ++result;
                      // Some ugly transformations are needed, here
                      int prime = i * 2 + 3;
                      for ( int j = prime * 3, k = prime * 2; j <= n; j += k)
                      sieve[j / 2 - 1] = 1;



                      return result;






                      share|improve this answer

























                      • Wow, 20 years after C99, and not even the most rudimentary VLAs... Looks like C++ is getting more and more behind C ;-) Afaik, there was once a proposal that would have made int array[length]; legal in C++, but even that proposal did not allow for multidimensional arrays, neither on the stack (int array2d[height][width]) nor on the heap (int (*array2d)[width] = new int[height][width];). Apparently, that proposal was never approved, even though C goes as far as to allow the multidimensional case (int (*array2d)[width] = malloc(height * sizeof(*array2d));) since 20 years ago...

                        – cmaster
                        7 hours ago











                      • @cmaster Well, that's debatable ;)

                        – Bob__
                        7 hours ago











                      • Yeah, I know. Especially since very few people actually understand the power of the C99 syntax - both of the top-scoring answers of the question you linked completely underestimate its value. Because, you see, C99 VLAs not just exist on the stack, they can also be allocated on the heap. I have already given an example of that, it's the last one. The real power comes from the fact that any C99 array type can have a runtime length, it can be pointed to or typedefed. And C99 does not care how many runtime length array types you nest, the indexing calculation comes out right.

                        – cmaster
                        3 hours ago











                      • Long story short: I really enjoy working with C++ for the most part, but when it comes to manipulating multidimensional arrays of plain data, (images, volumes, simulations), I'll just fall back to C99 for its VLA syntax.

                        – cmaster
                        3 hours ago













                      2












                      2








                      2







                      I'd like to add some remarks to the good answers already posted.




                      • The performance differences between std::vector<bool> and std::vector<char> may vary (a lot) between different library implementations and different sizes of the vectors.



                        See e.g. those quick benches: clang++ / libc++(LLVM) vs. g++ / libstdc++(GNU).



                      • This: bool flag[n+1]; declares a Variable Length Array, which (despites some performance advantages due to it beeing allocated in the stack) has never been part of the C++ standard, even if provided as an extension by some (C99 compliant) compilers.


                      • Another way to increase the performances could be to reduce the amount of calculations (and memory occupation) by considering only the odd numbers, given that all the primes except for 2 are odd.


                      If you can bare the less readable code, you could try to profile the following snippet.



                      int countPrimes(int n)

                      if ( n < 2 )
                      return 0;
                      // Sieve starting from 3 up to n, the number of odd number between 3 and n are
                      int sieve_size = n / 2 - 1;
                      std::vector<char> sieve(sieve_size);
                      int result = 1; // 2 is a prime.

                      for (int i = 0; i < sieve_size; ++i)

                      if ( sieve[i] == 0 )

                      // It's a prime, no need to scan the vector again
                      ++result;
                      // Some ugly transformations are needed, here
                      int prime = i * 2 + 3;
                      for ( int j = prime * 3, k = prime * 2; j <= n; j += k)
                      sieve[j / 2 - 1] = 1;



                      return result;






                      share|improve this answer















                      I'd like to add some remarks to the good answers already posted.




                      • The performance differences between std::vector<bool> and std::vector<char> may vary (a lot) between different library implementations and different sizes of the vectors.



                        See e.g. those quick benches: clang++ / libc++(LLVM) vs. g++ / libstdc++(GNU).



                      • This: bool flag[n+1]; declares a Variable Length Array, which (despites some performance advantages due to it beeing allocated in the stack) has never been part of the C++ standard, even if provided as an extension by some (C99 compliant) compilers.


                      • Another way to increase the performances could be to reduce the amount of calculations (and memory occupation) by considering only the odd numbers, given that all the primes except for 2 are odd.


                      If you can bare the less readable code, you could try to profile the following snippet.



                      int countPrimes(int n)

                      if ( n < 2 )
                      return 0;
                      // Sieve starting from 3 up to n, the number of odd number between 3 and n are
                      int sieve_size = n / 2 - 1;
                      std::vector<char> sieve(sieve_size);
                      int result = 1; // 2 is a prime.

                      for (int i = 0; i < sieve_size; ++i)

                      if ( sieve[i] == 0 )

                      // It's a prime, no need to scan the vector again
                      ++result;
                      // Some ugly transformations are needed, here
                      int prime = i * 2 + 3;
                      for ( int j = prime * 3, k = prime * 2; j <= n; j += k)
                      sieve[j / 2 - 1] = 1;



                      return result;







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 8 hours ago









                      John Kugelman

                      249k54407460




                      249k54407460










                      answered 8 hours ago









                      Bob__Bob__

                      5,24331527




                      5,24331527












                      • Wow, 20 years after C99, and not even the most rudimentary VLAs... Looks like C++ is getting more and more behind C ;-) Afaik, there was once a proposal that would have made int array[length]; legal in C++, but even that proposal did not allow for multidimensional arrays, neither on the stack (int array2d[height][width]) nor on the heap (int (*array2d)[width] = new int[height][width];). Apparently, that proposal was never approved, even though C goes as far as to allow the multidimensional case (int (*array2d)[width] = malloc(height * sizeof(*array2d));) since 20 years ago...

                        – cmaster
                        7 hours ago











                      • @cmaster Well, that's debatable ;)

                        – Bob__
                        7 hours ago











                      • Yeah, I know. Especially since very few people actually understand the power of the C99 syntax - both of the top-scoring answers of the question you linked completely underestimate its value. Because, you see, C99 VLAs not just exist on the stack, they can also be allocated on the heap. I have already given an example of that, it's the last one. The real power comes from the fact that any C99 array type can have a runtime length, it can be pointed to or typedefed. And C99 does not care how many runtime length array types you nest, the indexing calculation comes out right.

                        – cmaster
                        3 hours ago











                      • Long story short: I really enjoy working with C++ for the most part, but when it comes to manipulating multidimensional arrays of plain data, (images, volumes, simulations), I'll just fall back to C99 for its VLA syntax.

                        – cmaster
                        3 hours ago

















                      • Wow, 20 years after C99, and not even the most rudimentary VLAs... Looks like C++ is getting more and more behind C ;-) Afaik, there was once a proposal that would have made int array[length]; legal in C++, but even that proposal did not allow for multidimensional arrays, neither on the stack (int array2d[height][width]) nor on the heap (int (*array2d)[width] = new int[height][width];). Apparently, that proposal was never approved, even though C goes as far as to allow the multidimensional case (int (*array2d)[width] = malloc(height * sizeof(*array2d));) since 20 years ago...

                        – cmaster
                        7 hours ago











                      • @cmaster Well, that's debatable ;)

                        – Bob__
                        7 hours ago











                      • Yeah, I know. Especially since very few people actually understand the power of the C99 syntax - both of the top-scoring answers of the question you linked completely underestimate its value. Because, you see, C99 VLAs not just exist on the stack, they can also be allocated on the heap. I have already given an example of that, it's the last one. The real power comes from the fact that any C99 array type can have a runtime length, it can be pointed to or typedefed. And C99 does not care how many runtime length array types you nest, the indexing calculation comes out right.

                        – cmaster
                        3 hours ago











                      • Long story short: I really enjoy working with C++ for the most part, but when it comes to manipulating multidimensional arrays of plain data, (images, volumes, simulations), I'll just fall back to C99 for its VLA syntax.

                        – cmaster
                        3 hours ago
















                      Wow, 20 years after C99, and not even the most rudimentary VLAs... Looks like C++ is getting more and more behind C ;-) Afaik, there was once a proposal that would have made int array[length]; legal in C++, but even that proposal did not allow for multidimensional arrays, neither on the stack (int array2d[height][width]) nor on the heap (int (*array2d)[width] = new int[height][width];). Apparently, that proposal was never approved, even though C goes as far as to allow the multidimensional case (int (*array2d)[width] = malloc(height * sizeof(*array2d));) since 20 years ago...

                      – cmaster
                      7 hours ago





                      Wow, 20 years after C99, and not even the most rudimentary VLAs... Looks like C++ is getting more and more behind C ;-) Afaik, there was once a proposal that would have made int array[length]; legal in C++, but even that proposal did not allow for multidimensional arrays, neither on the stack (int array2d[height][width]) nor on the heap (int (*array2d)[width] = new int[height][width];). Apparently, that proposal was never approved, even though C goes as far as to allow the multidimensional case (int (*array2d)[width] = malloc(height * sizeof(*array2d));) since 20 years ago...

                      – cmaster
                      7 hours ago













                      @cmaster Well, that's debatable ;)

                      – Bob__
                      7 hours ago





                      @cmaster Well, that's debatable ;)

                      – Bob__
                      7 hours ago













                      Yeah, I know. Especially since very few people actually understand the power of the C99 syntax - both of the top-scoring answers of the question you linked completely underestimate its value. Because, you see, C99 VLAs not just exist on the stack, they can also be allocated on the heap. I have already given an example of that, it's the last one. The real power comes from the fact that any C99 array type can have a runtime length, it can be pointed to or typedefed. And C99 does not care how many runtime length array types you nest, the indexing calculation comes out right.

                      – cmaster
                      3 hours ago





                      Yeah, I know. Especially since very few people actually understand the power of the C99 syntax - both of the top-scoring answers of the question you linked completely underestimate its value. Because, you see, C99 VLAs not just exist on the stack, they can also be allocated on the heap. I have already given an example of that, it's the last one. The real power comes from the fact that any C99 array type can have a runtime length, it can be pointed to or typedefed. And C99 does not care how many runtime length array types you nest, the indexing calculation comes out right.

                      – cmaster
                      3 hours ago













                      Long story short: I really enjoy working with C++ for the most part, but when it comes to manipulating multidimensional arrays of plain data, (images, volumes, simulations), I'll just fall back to C99 for its VLA syntax.

                      – cmaster
                      3 hours ago





                      Long story short: I really enjoy working with C++ for the most part, but when it comes to manipulating multidimensional arrays of plain data, (images, volumes, simulations), I'll just fall back to C99 for its VLA syntax.

                      – cmaster
                      3 hours ago

















                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55745312%2fperformance-gap-between-vectorbool-and-array%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

                      Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп

                      ValueError: Expected n_neighbors <= n_samples, but n_samples = 1, n_neighbors = 6 (SMOTE) The 2019 Stack Overflow Developer Survey Results Are InCan SMOTE be applied over sequence of words (sentences)?ValueError when doing validation with random forestsSMOTE and multi class oversamplingLogic behind SMOTE-NC?ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)SmoteBoost: Should SMOTE be ran individually for each iteration/tree in the boosting?solving multi-class imbalance classification using smote and OSSUsing SMOTE for Synthetic Data generation to improve performance on unbalanced dataproblem of entry format for a simple model in KerasSVM SMOTE fit_resample() function runs forever with no result