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

[apex] New Rule: OperationWithHighCostInLoop #4675

Closed
tprouvot opened this issue Sep 13, 2023 · 0 comments · Fixed by #4677
Closed

[apex] New Rule: OperationWithHighCostInLoop #4675

tprouvot opened this issue Sep 13, 2023 · 0 comments · Fixed by #4677
Labels
a:new-rule Proposal to add a new built-in rule
Milestone

Comments

@tprouvot
Copy link
Contributor

tprouvot commented Sep 13, 2023

Proposed Rule Name: OperationWithHighCostInLoop

Proposed Category: Performance

Description:
Methods Schema.getGlobalDescribe() or Schema.describeSObjects should be called once per an apex transaction and should never be called inside a loop.

Code Sample: This should include code, that should be flagged by the rule. If possible, the "correct" code
according to this new rule should also be demonstrated.

//to avoid
Set<String> fieldNameSet = new Set<String> {'Id'};
		for (String fieldNameOrDefaultValue : fieldNameOrDefaultValueList) {
			if (Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap().containsKey(fieldNameOrDefaultValue.trim() )) {
				fieldNameSet.add(fieldNameOrDefaultValue);
			}
		}
//correct
Set<String> fieldNameSet = new Set<String> {'Id'};
		Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
		for (String fieldNameOrDefaultValue : fieldNameOrDefaultValueList) {
			if (fieldMap.containsKey(fieldNameOrDefaultValue.trim())) {
				fieldNameSet.add(fieldNameOrDefaultValue);
			}
		}

Additional Information:
See also: Why is Schema.describeSObjects(types) Slower Than Schema.getGlobalDescribe()?

Possible Properties:

  • Should this rule be customizable via properties?
@tprouvot tprouvot added the a:new-rule Proposal to add a new built-in rule label Sep 13, 2023
@adangel adangel changed the title [apex] AvoidGetGlobalDescribesInLoops [apex] New Rule: OperationWithHighCostInLoop Oct 18, 2023
@adangel adangel added this to the 7.0.0 milestone Oct 28, 2023
adangel added a commit to tprouvot/pmd that referenced this issue Oct 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
a:new-rule Proposal to add a new built-in rule
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants