What (tf) are the secrets behind PDF memory allocation (CGPDFDocumentRef)

Posted by Kai on Stack Overflow See other posts from Stack Overflow or by Kai
Published on 2011-01-12T12:26:53Z Indexed on 2011/01/13 3:54 UTC
Read the original article Hit count: 251

Filed under:
|
|
|

For a PDF reader I want to prepare a document by taking 'screenshots' of each page and save them to disc. First approach is

CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef) someURL);
for (int i = 1; i<=pageCount; i++) 
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];      
  CGPDFPageRef page = CGPDFDocumentGetPage(document, i);
  ...//getting + manipulating graphics context etc.
  ...
  CGContextDrawPDFPage(context, page);
  ...
  UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
  ...//saving the image to disc 
  [pool drain];
}
CGPDFDocumentRelease(document);

This results in a lot of memory which seems not to be released after the first run of the loop (preparing the 1st document), but no more unreleased memory in additional runs:

MEMORY BEFORE:          6 MB
MEMORY DURING 1ST DOC: 40 MB
MEMORY AFTER 1ST  DOC: 25 MB 
MEMORY DURING 2ND DOC: 40 MB
MEMORY AFTER 2ND  DOC: 25 MB
....

Changing the code to

for (int i = 1; i<=pageCount; i++) 
{
  CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef) someURL);
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];      
  CGPDFPageRef page = CGPDFDocumentGetPage(document, i);
  ...//getting + manipulating graphics context etc.
  ...
  CGContextDrawPDFPage(context, page);
  ...
  UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
  ...//saving the image to disc 
  CGPDFDocumentRelease(document);
  [pool drain];
}

changes the memory usage to

MEMORY BEFORE:          6 MB
MEMORY DURING 1ST DOC:  9 MB
MEMORY AFTER 1ST  DOC:  7 MB 
MEMORY DURING 2ND DOC:  9 MB
MEMORY AFTER 2ND  DOC:  7 MB
....

but is obviously a step backwards in performance.

When I start reading a PDF (later in time, different thread) in the first case no more memory is allocated (staying at 25 MB), while in the second case memory goes up to 20 MB (from 7).

In both cases, when I remove the CGContextDrawPDFPage(context, page); line memory is (nearly) constant at 6 MB during and after all preparations of documents.

Can anybody explain whats going on there?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about ipad