hyperoslo / Cache

:package: Nothing but Cache.
Other
2.96k stars 335 forks source link

DiskStorage file URL handling improvements #283

Closed shadowfacts closed 3 years ago

shadowfacts commented 3 years ago

This PR has a couple performance-related tweaks to how DiskStorage handles URLs.

The most significant is in the DiskStorage.makeFileName(for:) method. Currently, it uses the URL(fileURLWithPath:) initializer to extract the path extension (if any) from string keys. Per the NSURL docs, this does filesystem I/O for things like expanding relative paths and checking if the provided path is a directory on disk, and this is confirmed by multiple syscalls appearing up in a profile (below). Since this method doesn't actually care about what files exist on disk, we can cast the key to an NSString and use it's pathExtension property which merely interprets the string as a path, rather than interacting with the filesystem.

image

Similarly, in the entry(forKey:) method, we know that the file path is not going to be a directory so we can use the URL(fileURLWithPath:isDirectory:) initializer to specify that it's not, avoiding the unnecessary disk I/O that happens if the path does not end with a slash. Again from the NSURL docs:

This method assumes that path is a directory if it ends with a slash. If path does not end with a slash, the method examines the file system to determine if path is a file or a directory. If path exists in the file system and is a directory, the method appends a trailing slash. If path does not exist in the file system, the method assumes that it represents a file and does not append a trailing slash.

And, for completeness' sake, we can do the same in removeExpiredObjects because we know the DiskStorage's path is always going to be a directory.

3lvis commented 3 years ago

Thank you for your contribution, let's give it a try!