Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #306 Ensure list capacity

Preallocate memory in the list x for a minimum total capacity of 200 elements.

This is not possible in all languages. It is only meant as a performance optimization, should not change the length of x, and should not have any effect on correctness.

import "slices"
x = slices.Grow(x, 200)

This generic Grow func accepts x of any slice type
if cap(x) < 200 {
	y := make([]T, len(x), 200)
	copy(y, x)
	x = y
}

x has type []T.

x keeps the same length.
with Ada.Containers.Vectors;
declare
   X : Vector;
begin
   Reserve_Capacity (X, Capacity => 200);
end;

New implementation...
< >
programming-idioms.org