Correct usage of CachedValuesManager for caching PSI lookups?

Heey devs,

I’m using CachedValuesManager to cache expensive PSI lookups like PsiReference.resolve().
So I’m still new to the topic of caching, so I want to make sure I’m doing it right.

My questions:

Am I implementing caching correctly?

Is using each PsiElement (classConstant, methodReference) as the key to getCachedValue() the correct approach?

Will it be a problem if the method that handles caching is called thousands of times?

    public @Nullable PhpClass getPhpClassFrom(PsiElement classConstant) {
        return CachedValuesManager.getCachedValue(classConstant, () ->
            CachedValueProvider.Result.create(resolvePhpClassF(classConstant), PsiModificationTracker.MODIFICATION_COUNT)
        );
    }
    
    private @Nullable PhpClass resolvePhpClassF(@NotNull PsiElement classConstant) {
        if (!(classConstant instanceof ClassConstantReference classConstantReference)) {
            return null;
        }

        PhpExpression reference = classConstantReference.getClassReference();
        if (!(reference instanceof ClassReference classReference)) {
            return null;
        }

        PsiReference psiReference = classReference.getReference();
        if (psiReference == null) {
            return null;
        }

        PsiElement resolved = psiReference.resolve();
        if (resolved instanceof PhpClass resolvedPhpClass) {
            return resolvedPhpClass;
        }

        return null;
    }

Thx :slight_smile: