Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-45488

QVector initialization without default-constructed values for trivial types

    XMLWordPrintable

Details

    • Suggestion
    • Resolution: Fixed
    • P5: Not important
    • 6.0
    • 4.8.6, 5.3.2
    • None

    Description

      For trivial types, the QVector::QVector(int N) constructor gives a vector filled with N default-constructed values. E.g., QVector<double> vec(100) gives a 100-element vector with each element pre-initialized to 0.0. I suggest adding an additional constructor of the form QVector::QVector(int N,Qt::Initialization) that would allow the vector to contain N uninitialized values (trivial types only).

      As an example use case, consider a vector to contain 10M doubles. Currently, there are two options:

      int N = 10000000;
      
      //slow
      QVector<double> vec;
      vec.reserve(N);
      for(int i=0; i<N; i++)
           vec.append(...);
      
      //faster
      QVector<double> vec(N); //all N elements initialized to 0.0
      for(int i=0; i<N; i++)
           vec[i] = ...;
      

      The first case is slow; the overhead of append() is significant. The second case is reasonably fast, but there is still the overhead of initializing all N values to 0.0, even though they will be immediately overwritten in the next loop. When N is large (and particularly if this code is in a loop), the overhead becomes significant.

      Instead, for trivial types, an option like what follows would eliminate that extra overhead for cases in which the container will be manually initialized:

      //fastest
      QVector<double> vec(N,Qt::Uninitialized); //all N elements uninitialized
      for(int i=0; i<N; i++)
           vec[i] = ...;
      

      QVector is an example, but this could apply to other container classes as well.

      Attachments

        Issue Links

          No reviews matched the request. Check your Options in the drop-down menu of this sections header.

          Activity

            People

              Unassigned Unassigned
              kncrabtree Kyle Crabtree
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:

                Gerrit Reviews

                  There are no open Gerrit changes