Optimal way of filling `vtkFloatArray`


Ususally when we deal with containers it is recommended that we prepare size of the container before filling it. For example instead of std::vector::push_back() it is recommended to preliminary resize it and setting values using square brackets std::vector<float> v[0] = 12.

I assume that when we deal with vtkFloatArray we should stick to the same idea.
I can see that there is a vtkFloatArray::Resize() method and vtkFloatArray::SetValue(vtkIdType, ValueType). I thought that vtkIdType is something like an index of a value but I noticed that there is a difference between vtkFloatArray::SetValue(vtkIdType, ValueType) and vtkFloatArray::InsertNextValue(ValueType). If the array is filled with SetValue method and I addd it to the vtkImageData then I get strange range of values something like max 1e308 and min -1e308 (that is why my Slicer app fails). Probably vtkIdType is not an index?
But if I use InsertNextValue(ValueType) then everything is fine until I watch the size of an array:

    vtkNew<vtkFloatArray> array;
    auto s = array->GetSize();  //gives 0

    for (size_t z = 0; z < 10; z++){
      for (size_t x = 0; x < 20; x++){
        for (size_t y = 0; y < 30; y++){
          s = array->GetSize();  // gives 1, 3, 7 etc (why not 1, 2, 3, 4 ... ?)
// PS here I kept the idea of my code but some little things may differ like x,y,z ranges and assignement value (x+y+z)

The size of array increase nonlinearly… Why?

How should I fill the array and not loose perfomance?

You can have a look at VTK source code for best practices.

Non-linear increase of reserved memory is a good technique to reduce the number of reallocations, but if you know the array size in advance then you can call Allocate method to avoid all reallocations and extra memory usage.

1 Like

Didn’t know about that

I have just took a look to the source code and more carefully at the documentation, now I see a much better how vtk arrays work

Thank you

1 Like