Skip to content

Commit

Permalink
Cache local images into memory
Browse files Browse the repository at this point in the history
This introduces a cache for local image on macOS. There are no predefined limits set here (at least yet) since presumably we are loading a finite number of resources and we have the benefit of virtual memory swap on desktop so we don't really need to sweat a few extra megabytes of in-memory cache for images we know we'll need to repeatedly load.

Local images don't use the shared RN image cache, and on macOS there's no automatic in-memory cache for local resources (other than the OS-level disk cache) so the `RCTImageFromLocalBundleAssetURL` function will synchronously access the disk on the main thread many times over during thread switching in Messenger Desktop.

Added logging to confirmed cache works as expected in rn-tester, and instrumentation also confirms it.
  • Loading branch information
appden authored and christophpurrer committed Jul 26, 2022
1 parent d69fa5b commit 38a0e96
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions React/Base/RCTUtils.m
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#import "RCTAssert.h"
#import "RCTLog.h"

static const NSUInteger RCTMaxCachableImageCount = 100;

NSString *const RCTErrorUnspecified = @"EUNSPECIFIED";

// Returns the Path of Home directory
Expand Down Expand Up @@ -829,11 +831,29 @@ BOOL RCTIsLocalAssetURL(NSURL *__nullable imageURL)
return RCTImageFromLocalAssetURL(bundleImageUrl);
}

#if TARGET_OS_OSX // [TODO(macOS GH#774)
static NSCache<NSURL *, UIImage *> *RCTLocalImageCache()
{
static NSCache *imageCache;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
imageCache = [NSCache new];
imageCache.countLimit = RCTMaxCachableImageCount;
});
return imageCache;
}
#endif // ]TODO(macOS GH#774)

UIImage *__nullable RCTImageFromLocalAssetURL(NSURL *imageURL)
{
NSString *imageName = RCTBundlePathForURL(imageURL);
#if TARGET_OS_OSX // [TODO(macOS GH#774)
NSURL *bundleImageURL = nil;

UIImage *cachedImage = [RCTLocalImageCache() objectForKey:imageURL];
if (cachedImage) {
return cachedImage;
}
#endif // ]TODO(macOS GH#774)

NSBundle *bundle = nil;
Expand Down Expand Up @@ -911,6 +931,13 @@ BOOL RCTIsLocalAssetURL(NSURL *__nullable imageURL)
}
}
}

#if TARGET_OS_OSX // [TODO(macOS GH#774)
if (image) {
[RCTLocalImageCache() setObject:image forKey:imageURL];
}
#endif // ]TODO(macOS GH#774)

return image;
}

Expand Down

0 comments on commit 38a0e96

Please sign in to comment.