 : An Optimized ArrayStack
: An Optimized ArrayStack
 involves shifting (by
 involves shifting (by
 and
 and 
 ) and copying (by
) and copying (by 
 ) of data.  In the
implementations shown above, this was done using
) of data.  In the
implementations shown above, this was done using 
 loops. It turns
out that many programming environments have specific functions that
are very efficient at copying and moving blocks of data.  In the C
there are the
 loops. It turns
out that many programming environments have specific functions that
are very efficient at copying and moving blocks of data.  In the C
there are the 
 and
 and 
 functions. In C++
there is the
 functions. In C++
there is the 
 and algorithm.  In Java there is the
 and algorithm.  In Java there is the
 method.
 method.
  void resize() {
    array<T> b(max(1, 2*n));
    std::copy(a+0, a+n, b+0);
    a = b;
  }
  void add(int i, T x) {
    if (n + 1 > a.length) resize();
    std::copy_backward(a+i, a+n, a+n);
    a[i] = x;
    n++;
  }
These functions are usually highly optimized and may even use special
machine instructions that can do this copying much faster than we could do
using a 
 loop.  Although using these functions does not asymptotically
decrease the running times, it can still be a worthwhile optimization.
In the C++ implementations here, the use of
 loop.  Although using these functions does not asymptotically
decrease the running times, it can still be a worthwhile optimization.
In the C++ implementations here, the use of 
 resulted in speedups of a factor of 2-3 depending on the types of
operations performed.  Your mileage may vary.
resulted in speedups of a factor of 2-3 depending on the types of
operations performed.  Your mileage may vary.
opendatastructures.org