-1

I've encountered the problem that accessing data stored in heap memory performs really slow when the memory is frequently reallocated.

Reallocated every now and then

in comparison to

Once allocated

What could explain this behaviour?

Etan
  • 17,014
  • 17
  • 89
  • 148
  • Don't post images of text. This would have been a useful duplicate target for other questions that make the same mistake, but not without the code in a copy/pasteable (and readable for the blind, etc.) form. – Peter Cordes Feb 19 '20 at 06:19

1 Answers1

2

Possibly page fault issues. If you malloc a large block of RAM, the physical RAM will probably not be allocated straight away, some page table entries will be set. The physical RAM won't be allocated until you access a location in it for the first time. This involves

  • a page fault,
  • finding a physical memory page
  • zeroing every location on that page
  • updating the page table

This is an expensive operation in terms of time and will happen once per allocated page (550 x 4kbyte pages for the RAM you are allocating)

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • Why should there be more page faults when I reallocate the block more often? The iPad L2 cache is 1MB, so page faults should also occur for the static / stack memory. And the zeroing argument is only true for the calloc-ed memory. Malloc does not zero memory. Could you please add further explanations to your post? – Etan Dec 28 '11 at 17:04
  • @Etan: Presumably it is not reusing the same block of memory, or it is giving the memory back to the OS on deallocation (memory is limited on iDevices, so this is definitely a possibility). Static memory is permanently allocated and stack memory probably permanently allocated once it is used for the first time. – JeremyP Dec 28 '11 at 17:08
  • So basically the delayed allocation is what kills me here. This also explains why calloc is so much faster than memset or a {0} initializer. Whether it takes the same block of memory each time should not change the number of page faults since the page would be dirty after the free call even in the case where the old page is reused. – Etan Dec 28 '11 at 17:12