2

We are now investigating some performance issues for the client and trying to speed up their processes. One of the time consuming parts is apex sharing that we have there.

I am pretty sure that some time ago I have read that insert of apex shares can happen without any checks on existing ones because SF will make a check internally anyway and that it is possibly even better for performance to "brute force" insert apex shares instead of querying them first to eliminate duplicates.

For example:
There are 10 million Accounts and 20 million AccountShare records in the org. I need to share accounts A1-A20 with public group G. Which of these will be better?

1.

List<AccountShare> accShares = new List<AccountShare>();
for (Account a : accs) {
    AccountShare accSh = new AccountShare();
    accSh.AccountAccessLevel = 'Edit';
    accSh.AccountId = a.Id;
    accSh.RowCause = 'Manual';
    accSh.UserOrGroupId = pg.Id;
    accSh.OpportunityAccessLevel = 'None';
    accShares.add(accSh);
}
if (!accShares.isEmpty()) {
    insert accShares;
}

2.

List<AccountShare> accShares = new List<AccountShare>();
List<AccountShare> existingShares = [SELECT Id, AccountId 
                                     FROM AccountShare 
                                     WHERE AccountId IN :accs 
                                     AND UserOrGroupId = :pg.Id 
                                     AND AccountAccessLevel = 'Edit'];
Set<Id> sharedAccIds = new Set<Id>();
for (AccountShare accSh : existingShares) {
    sharedAccIds.add(accSh.Account);
}
for (Account a : accs) {
    // Only create a share if it does not exist yet
    if (!sharedAccIds.contains(a.Id)) {
        AccountShare accSh = new AccountShare();
        accSh.AccountAccessLevel = 'Edit';
        accSh.AccountId = a.Id;
        accSh.RowCause = 'Manual';
        accSh.UserOrGroupId = pg.Id;
        accSh.OpportunityAccessLevel = 'None';
        accShares.add(accSh);
    }
}
if (!accShares.isEmpty()) {
    insert accShares;
}

I am looking for documents that could prove/fail my thoughts about this "brute force" shares insert.

  • 1
    Did you try both the approaches on large set of data ? – RedDevil Sep 14 '18 at 9:15
  • 1
    if you are sharing account records to public groups then why dont you use in a configurable way? – Santanu Boral Sep 14 '18 at 12:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.