FFImageLoading icon indicating copy to clipboard operation
FFImageLoading copied to clipboard

Images load very slow on slower devices

Open ahohns opened this issue 10 years ago • 32 comments

Testing on a slow phone with what seems to be a much slower disk (slow write speeds) results in very slow image loading. With lots of images loading at once on first load (and when scrolling through new list items with images) it causes images to load in order quite a bit more slowly compared to newer/faster phones. This was noticed last week using alpha-6 and also this week using 2.0.0. Is it possible images are only returned once they've been written to disk? If not already, is it possible to return the image to be processed/displayed either before or during disk write?

ahohns avatar Dec 21 '15 04:12 ahohns

Yes. The image is updated after it's written to the disk. See: https://github.com/molinch/FFImageLoading/blob/d4182ea84c688eb7a3d1abc9c9d0b236dfe71c75/source/FFImageLoading.Shared/Cache/DownloadCache.cs#L94

There's also a lock which forces only one file writing operation at a time. That could be it. https://github.com/molinch/FFImageLoading/blob/master/source/FFImageLoading.Shared/Cache/DiskCache.cs#L221

It's faster to queue file writes (multiple concurrent file writes slow things down and sometimes cause too many files opened exceptions). Although, on very slow devices it could be exactly opposite.

@molinch @ahohns Do you have any suggestions?

daniel-luberda avatar Dec 21 '15 04:12 daniel-luberda

SemaphoreSlim fileWriteLock supports setting timeouts. Maybe we could set it to allow multiple file writes after specified time, unlocking other requests?

daniel-luberda avatar Dec 21 '15 05:12 daniel-luberda

Please wait before changing anything here @daniel-luberda. I would like to check a few things

molinch avatar Dec 21 '15 05:12 molinch

Maybe create a new memory stream after downloading using getbuffer and the new memorystream(byte[],offset,count) constructor (to share memory) and then skip await on save to disk (pass it the new memory stream) since even if we can't cache to disk, we probably are happy with downloaded file. I don't mind how long it takes to save the file, as long as it returns quickly with the image data so I can render the view

david-pershouse avatar Dec 21 '15 05:12 david-pershouse

@molinch Ok:) You could check that.

+1 for @david-pershouse idea

daniel-luberda avatar Dec 21 '15 05:12 daniel-luberda

So to sum it up:

  • we need a queue where disk writes gets queued
  • it should be non blocking
  • there is one entry of the queue processed at a time
  • if an item with the same key exists in the queue, or in the disk cache, then we should just skip it
  • Thread pool tasks or a dedicated thread. Ideally I would rather use the thread pool.

molinch avatar Dec 21 '15 20:12 molinch

@molinch Are you sure we need a queue? Maybe SemaphoreSlim is enough. We only need to move it to the async task which is not awaited. And that should be all. All in all FFImageloading deduplicates similar requests.

daniel-luberda avatar Dec 21 '15 21:12 daniel-luberda

If we want non blocking writes then yes it is needed

molinch avatar Dec 21 '15 21:12 molinch

What about this (psuedocode):

var stream = new Stream();
var streamCopy = stream.Copy(); 

// it's non-blocking, we don't await it. semaphore is static
var task = Task.Run(async () => {
  await semaphore.WaitAsync();
  await DoTheFileWrite(streamCopy);
  semaphore.Release();
})

return stream;

daniel-luberda avatar Dec 21 '15 21:12 daniel-luberda

I tried this approach. Works good! Take a look:

DownloadCache.cs

private async Task<MemoryStream> DownloadAndCacheAsync(string url, string filename, string filepath, CancellationToken token, TimeSpan? duration)
{
    if (duration == null)
        duration = new TimeSpan(30, 0, 0, 0); // by default we cache data 30 days

    int headersTimeout = ImageService.Config.HttpHeadersTimeout;
    int readTimeout = ImageService.Config.HttpReadTimeout - headersTimeout;

    var cancelHeadersToken = new CancellationTokenSource();
    cancelHeadersToken.CancelAfter(TimeSpan.FromSeconds(headersTimeout));
    var linkedHeadersToken = CancellationTokenSource.CreateLinkedTokenSource(token, cancelHeadersToken.Token);

    using (var response = await DownloadHttpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, linkedHeadersToken.Token).ConfigureAwait(false))
    {
        if (!response.IsSuccessStatusCode || response.Content == null)
            return null;

        var cancelReadToken = new CancellationTokenSource();
        cancelReadToken.CancelAfter(TimeSpan.FromSeconds(readTimeout));

        var responseBytes = await response.Content.ReadAsByteArrayAsync();
        var memoryStream = new MemoryStream(responseBytes, false);
        var fileWriteStream = new MemoryStream(responseBytes, false);

        memoryStream.Position = 0;
        fileWriteStream.Position = 0;

        var nonBlockingTask = _diskCache.AddOrUpdateAsync(filename, fileWriteStream, token, duration.Value).ConfigureAwait(false);

        memoryStream.Position = 0;
        return memoryStream;
    }
}

DiskCache.cs

public async Task AddOrUpdateAsync (string key, Stream stream, CancellationToken token, TimeSpan duration)
{
    key = SanitizeKey (key);

    bool existed = entries.ContainsKey (key);
    string filepath = Path.Combine(basePath, key);

    try
    {
        await fileWriteLock.WaitAsync();
        using (var fs = FileStore.GetOutputStream(filepath))
        {
            await stream.CopyToAsync(fs, BufferSize, token).ConfigureAwait(false);
        }
    }
    finally
    {
        stream.Dispose(); // stream needs to be disposed now !!!
        fileWriteLock.Release();
    }

    AppendToJournal (existed ? JournalOp.Modified : JournalOp.Created,
        key,
        DateTime.UtcNow,
        duration);
    entries[key] = new CacheEntry (DateTime.UtcNow, duration);
}

daniel-luberda avatar Dec 21 '15 22:12 daniel-luberda

What do you think about it? Should I commit this?

daniel-luberda avatar Dec 21 '15 23:12 daniel-luberda

Please don't. It needs to be tested against big lists first and ideally on devices with slow writes (we can simulate it with a delay).

molinch avatar Dec 21 '15 23:12 molinch

Ok, let me know about the results if you do some tests :)

daniel-luberda avatar Dec 21 '15 23:12 daniel-luberda

BTW: I don't think passing cancellation token to: var nonBlockingTask = _diskCache.AddOrUpdateAsync(filename, fileWriteStream, token, duration.Value).ConfigureAwait(false); is needed, if the file was downloaded it should be saved anyway.

daniel-luberda avatar Dec 21 '15 23:12 daniel-luberda

I agree even though writing to disk may slow down other operations. So that's the only negative effect, and why in the first place I passed the token.

We would go for the change you propose, without a queue, therefore I still think we need a list that stores pending writes:

  • If a file is pending for write then we shouldn't rewrite it (so we should stop any future write request for the same URL)

molinch avatar Dec 24 '15 15:12 molinch

@molinch Ok, I could make a commit with those changes (already using it when testing and there're no bugs). We could use a ConcurrentDictionary<string, Task> and check if key exists before running a new task and after write is removed from it. What do you think?

daniel-luberda avatar Dec 24 '15 18:12 daniel-luberda

Sounds good for me!

molinch avatar Dec 24 '15 20:12 molinch

Updated, non-blocking disk cache implementations which I was testing since a few days:

  • iOS/Android: https://github.com/molinch/FFImageLoading/commit/a5cb2f965736bea145d6c2fafb65612a72a16735
  • Windows: https://github.com/molinch/FFImageLoading/commit/82c9bf40cc9ee9a6818a18e5bfc40b4a38712d90

@molinch Do you accept it?

daniel-luberda avatar Dec 25 '15 13:12 daniel-luberda

https://www.nuget.org/packages/Xamarin.FFImageLoading.Forms/2.0.1-alpha1

daniel-luberda avatar Dec 26 '15 08:12 daniel-luberda

@daniel-luberda It's really nice. I have made a few changes in a00ee637c62a9aaf7c2798e148b9b6c694296a9e

We could possibly avoid the Task.Run: the methods called are truly async, IO is truly async, so it could be safe to not run on a separate thread.

molinch avatar Dec 26 '15 09:12 molinch