Reputation: 972
I need to load files in iOS, now I use the + [NSString stringWithContentsOfFile:]
.
The files are mostly 500kb to 5mb.
I load an approx. 4mb large file and Instruments and stopwatch told me it needs 1.5 seconds to load this file. In my opinion its a bit slow, is there a way to get the string faster?
EDIT:
I try some things and notice now, the creation of the NSString is my problem it takes 97% of the time and not the real loading from disk.
Upvotes: 3
Views: 566
Reputation: 104698
If you either know the encoding or can determine it (the API you use now is basic), you can just treat it as a char
buffer (in a manner which is encoding aware).
I'd begin by opening it using memory mapped data (mmap
, you can also approach this using NSData
). madvise
can be used to hint how you will access the file.
If memory mapped I/O consumes too much memory for your use, you should drop down to incremental reads, like C I/O facilities - fopen
, fread
, etc.. This will typically require more I/O events than memory mapped data (can be much slower, depending on how the data is accessed).
In both cases, you would treat the string as a C string -- don't simply convert the whole file to an NSString
upon opening.
Foundation has a lot of tricks, so make sure this actually improves performance for your specific use case.
If those solutions are too 'core for your use, just consider using smaller files instead (dividing existing files).
Upvotes: 3