Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce synchronous I/O when checking ImageCache.isCached #1480

Merged
merged 2 commits into from
Jul 5, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion Sources/Cache/DiskStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public enum DiskStorage {
public let directoryURL: URL

let metaChangingQueue: DispatchQueue

var maybeCached : Set<String>?

/// Creates a disk storage with the given `DiskStorage.Config`.
///
Expand All @@ -72,6 +74,17 @@ public enum DiskStorage {
metaChangingQueue = DispatchQueue(label: cacheName)

try prepareDirectory()

do {
maybeCached = Set()
try config.fileManager.contentsOfDirectory(atPath: directoryURL.path).forEach { (fileName) in
maybeCached?.insert(fileName)
}
} catch {
// Just disable the functionality if we fail to initialize it properly. This will just revert to
// the previous behaviour which is to check file existence on disk directly
maybeCached = nil
}
}

// Creates the storage folder.
Expand Down Expand Up @@ -135,6 +148,7 @@ public enum DiskStorage {
)
)
}
maybeCached?.insert(fileURL.lastPathComponent)
}

func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
Expand All @@ -150,6 +164,9 @@ public enum DiskStorage {
let fileManager = config.fileManager
let fileURL = cacheFileURL(forKey: key)
let filePath = fileURL.path
guard maybeCached?.contains(fileURL.lastPathComponent) ?? true else {
return nil
}
guard fileManager.fileExists(atPath: filePath) else {
return nil
}
Expand Down Expand Up @@ -228,7 +245,7 @@ public enum DiskStorage {
/// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered.
public func cacheFileURL(forKey key: String) -> URL {
let fileName = cacheFileName(forKey: key)
return directoryURL.appendingPathComponent(fileName)
return directoryURL.appendingPathComponent(fileName, isDirectory: false)
}

func cacheFileName(forKey key: String) -> String {
Expand Down