j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
175 stars 14 forks source link

Resizable allocatable arrays #326

Open PierUgit opened 6 months ago

PierUgit commented 6 months ago

Following a discussion on https://fortran-lang.discourse.group/t/enhancements-to-allocatable-arrays/

The basic idea is to have something similar to the C++ vectors, which can be dynamically resized while minimizing the occurences of malloc/copy/free, thanks to a significant overprovisionning of the capacity.

I came up with a description how it could work in Fortran, including a demonstration code (which is non standard, but nicely illustrates the proposed features): https://github.com/PierUgit/enhanced-allocatables

In particular, iteratively appending a element to an array would be much more efficient.

a = [a, x]
! replaced with
resize(a, append=x)

I do not copy/paste the whole description here, it's all in the README of the above repository.

I believe the change would be relatively simple for the compiler writers.

certik commented 6 months ago

Is the idea to add "capacity" into the array descriptor? Because you are not introducing any new types, so it would use the existing array types in Fortran, which means that only arrays that are implemented using a descriptor can be resized. The arrays that do not have a descriptor cannot be resized without a copy.

You can then reshape the existing array as long as it fits into the capacity (otherwise you copy & double the capacity), even a multidimensional one.

PierUgit commented 6 months ago

Is the idea to add "capacity" into the array descriptor?

Essentially, yes, this is what the compilers would have to do.

which means that only arrays that are implemented using a descriptor can be resized. The arrays that do not have a descriptor cannot be resized without a copy.

This pre-proposal is only for allocatable arrays: I guess they always have a descriptor?

certik commented 6 months ago

This pre-proposal is only for allocatable arrays: I guess they always have a descriptor?

I see, I think that will work. Yes, allocatable arrays usually have a descriptor in most compilers.

PierUgit commented 5 months ago

It's too early for a pull request, but I've prepared a draft proposal to have a basis for the discussion: https://github.com/PierUgit/enhanced-allocatables/blob/main/proposal.txt

PierUgit commented 5 months ago

Sorry, I messed a bit the topic by opening this issue while #318 was already opened :( ... Maybe one should be closed, just adding a reference to the other one. :