The culprit is the implementation of the _MemoryReadProc and how callers (indirectly use it).
E.g. PluginJPEG calls it like this (a lot) via fill_input_buffer:
read_proc(src->buffer, 1, INPUT_BUF_SIZE /* = 4096 */, src->infile)
This then leads to https://sourceforge.net/p/freeimage/svn/HEAD/tree/FreeImage/trunk/Source/FreeImage/FreeImageIO.cpp#l65 calling memcpy 4096 (for(x = 0; x < count; x++) memcpy(...)) times, copying one byte at a time. This is... not optimal... not optimal at all....
Loading a JPEG from memory roughly spends up to 40% of the run time in memcpy my profiler says (MSVC, x86_64)
I propose the following fix:
unsigned DLL_CALLCONV
_MemoryReadProc(void *buffer, const unsigned size, const unsigned count, fi_handle handle)
{
if (!handle || !size || !count) {
return 0;
}
auto mem_header = static_cast<FIMEMORYHEADER*>(static_cast<FIMEMORY*>(handle)->data);
if (!mem_header) {
return 0;
}
const auto req = MIN(
static_cast<size_t>(size) * count,
static_cast<size_t>(mem_header->file_length) - mem_header->current_position);
if (!req) {
return 0;
}
memcpy(buffer, static_cast<char*>(mem_header->data) + mem_header->current_position, req);
mem_header->current_position += req;
return static_cast<unsigned>(req / size);
}
With this change, loading a JPEG from memory roughly spends less than 2% in memcpy, which sounds even better when you consider the total runtime went down too, so it's 2% of less ;)
Given that loading an image by first writing it to a (fast) disk then loading it from disk (or OS diskcache really) is faster than loading it directly from memory in my tests, I consider this a bug and not just a feature request.
I haven't worked with SVN in so long, sorry there is no real patch.
Anonymous
Hi,
Thanks for this patch, it is now available in the SVN and will be included in the next version.
Hervé
Ticket moved from /p/freeimage/bugs/286/