Optimize containsKey -> get pattern

This commit is contained in:
Ivan Kochurkin
2021-10-19 21:32:54 +03:00
committed by TeamCityServer
parent 82591bb107
commit c13822a2c5
13 changed files with 49 additions and 33 deletions
@@ -485,19 +485,19 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
AccessorKey key = new AccessorKey(descriptor, superCallTarget, accessorKind); AccessorKey key = new AccessorKey(descriptor, superCallTarget, accessorKind);
// NB should check for property accessor factory first (or change property accessor tracking under propertyAccessorFactory creation) // NB should check for property accessor factory first (or change property accessor tracking under propertyAccessorFactory creation)
if (propertyAccessorFactories.containsKey(key)) { AccessorForPropertyDescriptorFactory propertyAccessorFactory = propertyAccessorFactories.get(key);
return (D) propertyAccessorFactories.get(key).getOrCreateAccessorIfNeeded(getterAccessorRequired, setterAccessorRequired); if (propertyAccessorFactory != null) {
return (D) propertyAccessorFactory.getOrCreateAccessorIfNeeded(getterAccessorRequired, setterAccessorRequired);
} }
if (accessors.containsKey(key)) { AccessorForCallableDescriptor<?> accessor = accessors.get(key);
AccessorForCallableDescriptor<?> accessor = accessors.get(key); if (accessor != null) {
assert accessorKind == AccessorKind.NORMAL || assert accessorKind == AccessorKind.NORMAL ||
accessor instanceof AccessorForPropertyBackingField : "There is already exists accessor with isForBackingField = false in this context"; accessor instanceof AccessorForPropertyBackingField : "There is already exists accessor with isForBackingField = false in this context";
return (D) accessor; return (D) accessor;
} }
String nameSuffix = SyntheticAccessorUtilKt.getAccessorNameSuffix(descriptor, key.superCallLabelTarget, accessorKind); String nameSuffix = SyntheticAccessorUtilKt.getAccessorNameSuffix(descriptor, key.superCallLabelTarget, accessorKind);
AccessorForCallableDescriptor<?> accessor;
if (descriptor instanceof SimpleFunctionDescriptor) { if (descriptor instanceof SimpleFunctionDescriptor) {
accessor = new AccessorForFunctionDescriptor((FunctionDescriptor) descriptor, contextDescriptor, superCallTarget, nameSuffix, accessorKind); accessor = new AccessorForFunctionDescriptor((FunctionDescriptor) descriptor, contextDescriptor, superCallTarget, nameSuffix, accessorKind);
} }
@@ -59,7 +59,8 @@ public class RemappingClassBuilder extends DelegatingClassBuilder {
@Nullable String signature, @Nullable String signature,
@Nullable Object value @Nullable Object value
) { ) {
if (spilledCoroutineVariables.containsKey(name)) return spilledCoroutineVariables.get(name); FieldVisitor spilledCoroutineVariable = spilledCoroutineVariables.get(name);
if (spilledCoroutineVariable != null) return spilledCoroutineVariable;
FieldRemapper field = new FieldRemapper( FieldRemapper field = new FieldRemapper(
builder.newField(origin, access, name, this.remapper.mapDesc(desc), this.remapper.mapSignature(signature, true), value), builder.newField(origin, access, name, this.remapper.mapDesc(desc), this.remapper.mapSignature(signature, true), value),
@@ -30,7 +30,7 @@ class TypeRemapper private constructor(
private val typeParametersMapping = hashMapOf<String, TypeParameter>() private val typeParametersMapping = hashMapOf<String, TypeParameter>()
fun addMapping(type: String, newType: String) { fun addMapping(type: String, newType: String) {
typeMapping.put(type, newType) typeMapping[type] = newType
} }
fun hasNoAdditionalMapping(type: String): Boolean { fun hasNoAdditionalMapping(type: String): Boolean {
@@ -111,9 +111,10 @@ class BuilderFactoryForDuplicateSignatureDiagnostics(
signatures: MultiMap<RawSignature, JvmDeclarationOrigin> signatures: MultiMap<RawSignature, JvmDeclarationOrigin>
) { ) {
for (predefinedSignature in PREDEFINED_SIGNATURES) { for (predefinedSignature in PREDEFINED_SIGNATURES) {
if (!signatures.containsKey(predefinedSignature)) continue val signature = signatures[predefinedSignature]
if (signature.isEmpty()) continue
val origins = signatures[predefinedSignature] + JvmDeclarationOrigin.NO_ORIGIN val origins = signature + JvmDeclarationOrigin.NO_ORIGIN
val diagnostic = computeDiagnosticToReport(classOrigin, classInternalName, predefinedSignature, origins) ?: continue val diagnostic = computeDiagnosticToReport(classOrigin, classInternalName, predefinedSignature, origins) ?: continue
diagnostics.report(ErrorsJvm.CONFLICTING_INHERITED_JVM_DECLARATIONS.on(diagnostic.element, diagnostic.data)) diagnostics.report(ErrorsJvm.CONFLICTING_INHERITED_JVM_DECLARATIONS.on(diagnostic.element, diagnostic.data))
@@ -51,12 +51,16 @@ public class StringSwitchCodegen extends SwitchCodegen {
assert constant instanceof StringValue : "guaranteed by usage contract"; assert constant instanceof StringValue : "guaranteed by usage contract";
int hashCode = constant.hashCode(); int hashCode = constant.hashCode();
List<StringSwitchCodegen.Entry> hashCodesToEntry;
if (!transitionsTable.containsKey(hashCode)) { if (!transitionsTable.containsKey(hashCode)) {
transitionsTable.put(hashCode, new Label()); transitionsTable.put(hashCode, new Label());
hashCodesToEntries.put(hashCode, new ArrayList<>()); hashCodesToEntry = new ArrayList<>();
hashCodesToEntries.put(hashCode, hashCodesToEntry);
} else {
hashCodesToEntry = hashCodesToEntries.get(hashCode);
} }
hashCodesToEntries.get(hashCode).add(new Entry(((StringValue) constant).getValue(), entryLabel, entry)); hashCodesToEntry.add(new Entry(((StringValue) constant).getValue(), entryLabel, entry));
} }
@Override @Override
@@ -34,8 +34,9 @@ class JavacWrapperKotlinResolverImpl(private val lightClassGenerationSupport: Li
private val supersCache = hashMapOf<KtClassOrObject, List<ClassId>>() private val supersCache = hashMapOf<KtClassOrObject, List<ClassId>>()
override fun resolveSupertypes(classOrObject: KtClassOrObject): List<ClassId> { override fun resolveSupertypes(classOrObject: KtClassOrObject): List<ClassId> {
if (supersCache.containsKey(classOrObject)) { val cachedItem = supersCache[classOrObject]
return supersCache[classOrObject]!! if (cachedItem != null) {
return cachedItem
} }
val classDescriptor = val classDescriptor =
@@ -117,10 +117,11 @@ object FirMemberPropertiesChecker : FirClassChecker() {
} }
for (propertySymbol in memberPropertySymbols) { for (propertySymbol in memberPropertySymbols) {
if (map.containsKey(propertySymbol)) { val item = map[propertySymbol]
if (item != null) {
// Accumulation: // Accumulation:
// range join for class constructors, range plus for class's anonymous initializers and property initializations // range join for class constructors, range plus for class's anonymous initializers and property initializations
map[propertySymbol] = acc.invoke(map[propertySymbol]!!, info[propertySymbol] ?: EventOccurrencesRange.ZERO) map[propertySymbol] = acc.invoke(item, info[propertySymbol] ?: EventOccurrencesRange.ZERO)
} else { } else {
// Initial assignment. // Initial assignment.
// NB: we should not use `acc` here to not weaken ranges. For example, if we visit one and only constructor where // NB: we should not use `acc` here to not weaken ranges. For example, if we visit one and only constructor where
@@ -211,8 +211,9 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
} }
} }
if (contributedFunctionsInSupertypes.containsKey(EQUALS)) { val equalsContributedFunction = contributedFunctionsInSupertypes[EQUALS]
result.add(contributedFunctionsInSupertypes.getValue(EQUALS)) if (equalsContributedFunction != null) {
result.add(equalsContributedFunction)
val equalsFunction = createSyntheticIrFunction( val equalsFunction = createSyntheticIrFunction(
EQUALS, EQUALS,
components.irBuiltIns.booleanType, components.irBuiltIns.booleanType,
@@ -222,8 +223,9 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
irClass.declarations.add(equalsFunction) irClass.declarations.add(equalsFunction)
} }
if (contributedFunctionsInSupertypes.containsKey(HASHCODE_NAME)) { val hashcodeNameContributedFunction = contributedFunctionsInSupertypes[HASHCODE_NAME]
result.add(contributedFunctionsInSupertypes.getValue(HASHCODE_NAME)) if (hashcodeNameContributedFunction != null) {
result.add(hashcodeNameContributedFunction)
val hashCodeFunction = createSyntheticIrFunction( val hashCodeFunction = createSyntheticIrFunction(
HASHCODE_NAME, HASHCODE_NAME,
components.irBuiltIns.intType, components.irBuiltIns.intType,
@@ -232,8 +234,9 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
irClass.declarations.add(hashCodeFunction) irClass.declarations.add(hashCodeFunction)
} }
if (contributedFunctionsInSupertypes.containsKey(TO_STRING)) { val toStringContributedFunction = contributedFunctionsInSupertypes[TO_STRING]
result.add(contributedFunctionsInSupertypes.getValue(TO_STRING)) if (toStringContributedFunction != null) {
result.add(toStringContributedFunction)
val toStringFunction = createSyntheticIrFunction( val toStringFunction = createSyntheticIrFunction(
TO_STRING, TO_STRING,
components.irBuiltIns.stringType, components.irBuiltIns.stringType,
@@ -48,7 +48,8 @@ abstract class AbstractFirOverrideScope(
// Receiver is super-type function here // Receiver is super-type function here
protected open fun FirCallableSymbol<*>.getOverridden(overrideCandidates: Set<FirCallableSymbol<*>>): FirCallableSymbol<*>? { protected open fun FirCallableSymbol<*>.getOverridden(overrideCandidates: Set<FirCallableSymbol<*>>): FirCallableSymbol<*>? {
if (overrideByBase.containsKey(this)) return overrideByBase[this] val overrideByBaseItem = overrideByBase[this]
if (overrideByBaseItem != null) return overrideByBaseItem
val baseDeclaration = (this as FirBasedSymbol<*>).fir as FirCallableDeclaration val baseDeclaration = (this as FirBasedSymbol<*>).fir as FirCallableDeclaration
val override = overrideCandidates.firstOrNull { val override = overrideCandidates.firstOrNull {
@@ -161,8 +161,9 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val
instruction.owner = this instruction.owner = this
if (instruction is KtElementInstruction) { if (instruction is KtElementInstruction) {
if (!representativeInstructions.containsKey(instruction.element)) { val element = instruction.element
representativeInstructions.put(instruction.element, instruction) if (!representativeInstructions.containsKey(element)) {
representativeInstructions[element] = instruction
} }
} }
@@ -430,8 +431,9 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val
private fun copyInstruction(instruction: Instruction, originalToCopy: Map<Label, PseudocodeLabel>): Instruction { private fun copyInstruction(instruction: Instruction, originalToCopy: Map<Label, PseudocodeLabel>): Instruction {
if (instruction is AbstractJumpInstruction) { if (instruction is AbstractJumpInstruction) {
val originalTarget = instruction.targetLabel val originalTarget = instruction.targetLabel
if (originalToCopy.containsKey(originalTarget)) { val item = originalToCopy[originalTarget]
return instruction.copy(originalToCopy[originalTarget]!!) if (item != null) {
return instruction.copy(item)
} }
} }
if (instruction is NondeterministicJumpInstruction) { if (instruction is NondeterministicJumpInstruction) {
@@ -54,10 +54,10 @@ private class StaticDefaultFunctionLowering(val context: JvmBackendContext) : Ir
) )
override fun visitReturn(expression: IrReturn): IrExpression { override fun visitReturn(expression: IrReturn): IrExpression {
val irFunction = context.staticDefaultStubs[expression.returnTargetSymbol]
return super.visitReturn( return super.visitReturn(
if (context.staticDefaultStubs.containsKey(expression.returnTargetSymbol)) { if (irFunction != null) {
with(expression) { with(expression) {
val irFunction = context.staticDefaultStubs[expression.returnTargetSymbol]!!
IrReturnImpl(startOffset, endOffset, type, irFunction.symbol, value) IrReturnImpl(startOffset, endOffset, type, irFunction.symbol, value)
} }
} else { } else {
@@ -207,9 +207,9 @@ class JavacWrapper(
javaClass.virtualFile?.let { if (it in scope) return javaClass } javaClass.virtualFile?.let { if (it in scope) return javaClass }
} }
if (symbolBasedClassesCache.containsKey(classId)) { val javaClass = symbolBasedClassesCache[classId]
val javaClass = symbolBasedClassesCache[classId] if (javaClass != null) {
javaClass?.virtualFile?.let { file -> javaClass.virtualFile?.let { file ->
if (file in scope) return javaClass if (file in scope) return javaClass
} }
} }
@@ -309,7 +309,8 @@ class JavacWrapper(
} }
private fun findPackageInSymbols(fqName: String): SymbolBasedPackage? { private fun findPackageInSymbols(fqName: String): SymbolBasedPackage? {
if (symbolBasedPackagesCache.containsKey(fqName)) return symbolBasedPackagesCache[fqName] val cachedSymbolBasedPackage = symbolBasedPackagesCache[fqName]
if (cachedSymbolBasedPackage != null) return cachedSymbolBasedPackage
fun findSimplePackageInSymbols(fqName: String): SimpleSymbolBasedPackage? { fun findSimplePackageInSymbols(fqName: String): SimpleSymbolBasedPackage? {
elements.getPackageElement(fqName)?.let { symbol -> elements.getPackageElement(fqName)?.let { symbol ->
@@ -31,7 +31,8 @@ class ClassifierResolver(private val javac: JavacWrapper) {
private val beingResolved = hashSetOf<Tree>() private val beingResolved = hashSetOf<Tree>()
fun resolve(tree: Tree, unit: CompilationUnitTree, containingElement: JavaElement): JavaClassifier? { fun resolve(tree: Tree, unit: CompilationUnitTree, containingElement: JavaElement): JavaClassifier? {
if (cache.containsKey(tree)) return cache[tree] val result = cache[tree]
if (result != null) return result
if (tree in beingResolved) return null if (tree in beingResolved) return null
beingResolved(tree) beingResolved(tree)