[MOAB-dev] variable-length arrays

Jason Kraftcheck kraftche at cae.wisc.edu
Tue Nov 17 16:01:13 CST 2009


After reading Jed's reply, I tried a few simple timing tests.  The
variable-size stack offset when using VLAs seems to result in worse
performance than a much safer stack/heap combined approach such as:
  void foo( int n ) {
    int fixed_array[100];
    std::vector<int> dyn_array;
    int* array = fixed_array;
    if (n > sizeof(fixed_array)/sizeof(int)) {
      dyn_array.resize(n);
      array = &dyn_array[0];
    }
    ...
  }

And this solution is amiable to encapsulation in a template class, unlike
VLAs.  So it appears that it is best to continue to avoid the use of VLAs.

- jason



Jason Kraftcheck wrote:
> Beginning with the C99 standard, the C language has had support for
> automatic-duration variable-length arrays.  For example:
>   void foo( int n ) {
>     int array[n]; // 'n' is *not* a constant
>     ...
>   }
> 
> No C++ standard incorporates this feature yet.  However, given that a) it is
> common for much code to be shared between C and C++ compilers from the same
> vendor, b) this feature has been in the C standard for a decade, and c) this
> feature will be included in the next C++ standard, it seems likely that many
>  C++ compilers support this feature now (e.g The Gnu compiler does.)
> 
> It is possible to get the same functionality in c++ using std::vector
> (except for arrays of bool, and assuming the time to zero the memory isn't
> significant).  However, std::vector allocates storage on the heap while a
> automatic array will (typically) be allocated on the stack.  For a few cases
> involving tight loops where the performance with heap allocation is
> unacceptable, it would be nice to be able to use var-len auto arrays.
> 
> We have not this feature anywhere in MOAB or CGM so far because of possible
> portability issues.  Does anyone have any experience with using
> variable-length automatic arrays in C++ code that is built on diverse systems?
> 
> - jason
> 


-- 
"A foolish consistency is the hobgoblin of little minds" - Ralph Waldo Emerson



More information about the moab-dev mailing list