Just an idea I just had.
Maybe memory allocators have been doing that already for the past 300 years. In that case: Good job memory allocator people, keep on keeping on!
When allocating memory, and anticipating that you need more in the future, you might want to allocate more memory than you currently need.
struct Arr
make_image()
{
struct Arr arr = {
.data = malloc(10000),
.cap = 10000,
.len = 0,
};
return arr;
}
struct Arr
make_key()
{
struct Arr arr = {
.data = malloc(128),
.cap = 128,
.len = 64,
};
return arr;
}
A drawback of this approach is that the allocator can never give you less memory than you request. It can only optimize by giving you more memory.
struct Arr
make_image()
{
struct Arr arr = {
.data = malloc(0),
.len = 0,
};
return arr;
}
struct Arr
make_key()
{
struct Arr arr = {
.data = malloc(64),
.len = 64,
};
return arr;
}
In the two examples above,
the malloc(0)
call could yield
e.g. 10_000 bytes of memory.
It could do that by analyzing the stack,
seeing that it was called from make_image
.
And by having analyzed in the past
that calls from make_image
usually need memory areas that big.
The malloc(64)
call could yield
e.g. 128 bytes of memory
because calls from make_key
usually don't need more than that.
This analysis could include the call stack not just the direct caller.
realloc
, even free
, calls can benefit from the same mechanism.