Skip to content

Conversation

@straight-shoota
Copy link
Member

Implements #16203 (comment)

Pointer.malloc initializes the allocated memory with zeros, so we can skip the explicit implementation if the representation of value is all zeroes.

This should make Pointer(T).malloc(size, value) (almost) as efficient as Pointer(T).malloc(size) when value is all zeros.

@ysbaddaden
Copy link
Contributor

For the record:

Pointer.malloc initializes the allocated memory with zeros...

... if we required src/gc.cr to define __crystal_malloc64 that will call the GC that will zero the allocation (be it gc/boehm or gc/none). Otherwise the compiler calls LibC.malloc and the memory is uninitialized 🤷

Now, that's a very edge case and we probably don't need to care about it.

@HertzDevil
Copy link
Contributor

HertzDevil commented Nov 6, 2025

This edge case is present in all codegen specs that do not require the prelude (in fact I believe __crystal_malloc64 was invented precisely for reducing boilterplate in them). Still this is only relevant if a spec tries to require pointer.cr directly I guess?

@ysbaddaden
Copy link
Contributor

@HertzDevil Yes, that's why I brought it up, but the compiler specs load the whole prelude when they need something from stdlib, and never load src/pointer.cr directly or indirectly.

Still, we might want to check for {% if @toplevel.has_constant?(:GC) %}.

@straight-shoota
Copy link
Member Author

straight-shoota commented Nov 6, 2025

We were discussing potential changes to memory allocation characteristics to more explicitly handle when memory needs to be zeroed out and when not (#14687 and #14677).
So potentially there might be changes in the future. But in the current state of things, it should be assumed that Pointer.malloc allocates zeroed memory. We even do that explicitly in gc_none.

@ysbaddaden
Copy link
Contributor

Yeah, it's a real edge case. It only happens when you manually require src/pointer.cr and don't require src/gc.cr and don't have a custom __crystal_malloc64 (or one that doesn't zero)... which neither of the compiler specs or even nanolib do, so... it's definitely fine 👍

@straight-shoota
Copy link
Member Author

Merged master with #16338 and resolved conflict

@ysbaddaden ysbaddaden added this to the 1.19.0 milestone Nov 10, 2025
@straight-shoota straight-shoota merged commit e36c936 into crystal-lang:master Nov 12, 2025
40 checks passed
@straight-shoota straight-shoota deleted the perf/pointer.malloc-zero branch November 12, 2025 10:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants