Menu ▾ ▴

#134 FreeImage_LoadFromMemory is unnecessarily slow

None
pending
None
5
2019-04-07
2018-12-17
RealDolos
No

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.

Discussion

  • Hervé Drolon

    Hervé Drolon - 2019-01-03
    • assigned_to: Hervé Drolon
    • Group: -->
     
  • Hervé Drolon

    Hervé Drolon - 2019-04-07
    • status: open --> pending
     
  • Hervé Drolon

    Hervé Drolon - 2019-04-07

    Hi,

    Thanks for this patch, it is now available in the SVN and will be included in the next version.

    Hervé

     
  • Hervé Drolon

    Hervé Drolon - 2019-04-07

    Ticket moved from /p/freeimage/bugs/286/

     

Anonymous
Anonymous

Add attachments
Cancel