Skip to content

Commit 28f6d8b

Browse files
Optimize Cache Insertion with try_emplace for Reduced Lookups
for the functions- insertEntryForFilename() , insertRealPathForFilename() Replaced `Cache.insert()` with `Cache.try_emplace()` to reduce redundant lookups Improved efficiency by avoiding unnecessary copying of values when the key already exists
1 parent fbf0276 commit 28f6d8b

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -247,15 +247,16 @@ class DependencyScanningFilesystemLocalCache {
247247
insertEntryForFilename(StringRef Filename,
248248
const CachedFileSystemEntry &Entry) {
249249
assert(llvm::sys::path::is_absolute_gnu(Filename));
250-
auto [It, Inserted] = Cache.insert({Filename, {&Entry, nullptr}});
251-
auto &[CachedEntry, CachedRealPath] = It->getValue();
252-
if (!Inserted) {
253-
// The file is already present in the local cache. If we got here, it only
254-
// contains the real path. Let's make sure the entry is populated too.
255-
assert((!CachedEntry && CachedRealPath) && "entry already present");
256-
CachedEntry = &Entry;
257-
}
258-
return *CachedEntry;
250+
251+
auto &[CachedEntry, CachedRealPath] = Cache.try_emplace(
252+
Filename, &Entry, nullptr).first->getValue();
253+
254+
if (!CachedEntry) {
255+
assert((!CachedEntry && CachedRealPath) && "entry already present");
256+
CachedEntry = &Entry;
257+
}
258+
259+
return *CachedEntry;
259260
}
260261

261262
/// Returns real path associated with the filename or nullptr if none is
@@ -272,14 +273,14 @@ class DependencyScanningFilesystemLocalCache {
272273
insertRealPathForFilename(StringRef Filename,
273274
const CachedRealPath &RealPath) {
274275
assert(llvm::sys::path::is_absolute_gnu(Filename));
275-
auto [It, Inserted] = Cache.insert({Filename, {nullptr, &RealPath}});
276-
auto &[CachedEntry, CachedRealPath] = It->getValue();
277-
if (!Inserted) {
278-
// The file is already present in the local cache. If we got here, it only
279-
// contains the entry. Let's make sure the real path is populated too.
276+
auto &[CachedEntry, CachedRealPath] = Cache.try_emplace(
277+
Filename, nullptr, &RealPath).first->getValue();
278+
279+
if (!CachedRealPath) {
280280
assert((!CachedRealPath && CachedEntry) && "real path already present");
281281
CachedRealPath = &RealPath;
282282
}
283+
283284
return *CachedRealPath;
284285
}
285286
};

0 commit comments

Comments
 (0)