Why do dynamic arrays in C ++ and Java have different initial capabilities?

So, I was looking for how a dynamic array works in general. I found two different concepts.

In c ++

In C ++, a dynamic array is usually implemented by vectors. Vectors set the capacitance to 0, increment the counter to insert a new element, and then double the size of the capacitance for new inserts.

vector.h

/*
 * Implementation notes: Vector constructor and destructor
 * -------------------------------------------------------
 * The constructor allocates storage for the dynamic array and initializes
 * the other fields of the object.  The destructor frees the memory used
 * for the array.
 */

template <typename ValueType>
Vector<ValueType>::Vector() {
   count = capacity = 0;
   elements = NULL;
}

To expand the size of the vector

/*
 * Implementation notes: expandCapacity
 * ------------------------------------
 * This function doubles the array capacity, copies the old elements into
 * the new array, and then frees the old one.
 */

template <typename ValueType>
void Vector<ValueType>::expandCapacity() {
   capacity = max(1, capacity * 2);
   ValueType *array = new ValueType[capacity];
   for (int i = 0; i < count; i++) {
      array[i] = elements[i];
   }
   if (elements != NULL) delete[] elements;
   elements = array;
}

In java

java arrayList, 10 ( JVM), , . , , 10, , . , .

vector.h 0? (, 10) , 0, , - .

, , 10.

: - 0? , anyways , .

+4
3

, std::vector ( , ). , ~ 10 , std::vector::reserve:

std::vector<int> vec;
vec.reserve(10);

, Java -, afaik, Java , ++, , / .

+6

0?

0 , . ++ (AFAIK), .

, / 0-. , , ++:

, .

(.: B. Stroustrup: ++. Addison Wesley, ISBN 0-201-54330-3. 1994 .)

- .

, ++ , , , , "".

@yurikilocheck, std::vector reserve(), - , "", - . , ( ) .

:. , std::vector , . .

+3

I used an implementation that stores the default value of 32 elements per vector. It was an embedded implementation of Sun C ++ STL. It was a disaster. I had a perfectly reasonable program, which by its nature should have had about a hundred thousand of these vectors. He did not have enough memory. And it should have been perfect, because of those hundreds of thousands of elements, only a small percentage had these vectors not empty.

So, from personal experience, 0 is the best default vector size.

+3
source

Source: https://habr.com/ru/post/1683286/


All Articles