Apex Algorithms: Tips & Tricks
Mary Scotton
Developer Evangelist
salesforce.com
@rockchick322004
Gonzalo Abruna
Developer & Analyst
4C Consulting (Belgium)
@GonzaloAbruna
Safe Harbor
Safe harbor statement under the Private Securities Litigation Reform Act of 1995:
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties
materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results
expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed
forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items
and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning
new, planned, or upgraded services or technology developments and customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new
functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our
operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any
litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our
relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our
service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger
enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our
annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter.
These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section
of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently
available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based
upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking
statements.
Agenda
•  Top Coder Challenge
•  Optimize SOQL queries
•  How to optimize an algorithm: tips & tricks
•  Summary
•  References
•  Q&A
Use to
uce a
video,
A, etc. Use Case: Mother-Son Bowling Event
Assign each attendee to 1 of 30 lanes, ordered by grade
Place
er or
go in
ea of
ered
ntally
Gonzalo Abruna
Developer & Analyst, 4C Consulting (Belgium)
Optimize SOQL queries
SOQL Limits
•  100 SOQL queries per transaction (200 if transaction is asynchronous)
•  50.000 rows retrieved by SOQL queries
•  120 seconds maximum SOQL query run time
Optimize SOQL queries
Data Model
Optimize SOQL queries
Requirements: Sample Scenario
•  Query all the Contacts that have worked for an Account, via join object
•  For those Contacts, get all the Accounts they have worked for
Optimize SOQL queries
Solution #1
•  Upsides
–  Easy to implement
•  Downsides
–  Many loops
–  Many SOQLs
–  Bad performance
Optimize SOQL queries
Solution #2
•  Upsides
–  Less SOQL queries
–  Less loops (important for complex algorithms)
•  Downsides
–  Not much better than Solution #1
–  SOQL Limit: “In a SOQL query with parent-child relationship sub-queries, each parent-child
relationship counts as an additional query. These types of queries have a limit of three times the
number for top-level queries. The row counts from these relationship queries contribute to the row
counts of the overall code execution. In addition to static SOQL statements, calls to the following
methods count against the number of SOQL statements issued in a request.”
Optimize SOQL queries
Solution #3
•  Upsides
–  The most efficient
–  Less SOQL queries
–  Less loops (important for complex algorithms)
•  Downsides
–  Data structures may be required to represent the data
Representing the Data
•  Upsides
–  Avoids unnecessary loops
–  Direct access to the records
–  Easier to handle than lists without key
•  Downsides
–  Be careful with null pointer exceptions and reference to null object
–  Maps are not ordered
Solution #3, Part 2: Using Map<Id, List<sObject>>
How to Optimize an Algorithm
•  Use Map<Id, sObject> in SOQL queries
List<Account> listAccounts = [SELECT Id, Name FROM Account];
Map<Id, Account> mapAccounts = new Map<Id, Account>([SELECT Id, Name FROM
Account]);
•  Estimate how big your data is & test empty values scenario
•  Avoid unnecessary loops: try to reuse loops without losing readability of code
Top Tricks
How to Optimize an Algorithm
•  Put conditions in SOQL queries, not in if statements
List<Account> listAccounts = [SELECT Id, Name, Type FROM Account];
for(Account acc : listAccounts){
if(acc.Type == ‘Prospect’){…}
}
VS
List<Account> listAccounts = [SELECT Id, Name, Type FROM Account WHERE Type = ‘Prospect’];
Top Tricks
How to Optimize an Algorithm
•  Query only the fields that you need
•  Try to avoid putting formula fields on a WHERE clause
•  Parent-Child SOQL to avoid loops
–  Example: get the three newest Contacts per Account
Top Tricks
Summary
•  Every algorithm is different
•  Think before coding
•  Be aware of limits
•  Readability of code is important
•  Complex algorithms can be broken down into smaller and easier (divide & conquer)
•  The place of an algorithm is critical
References
•  Developer blogs https://developer.salesforce.com/blogs/
•  Force.com Apex developer guide.
http://www.salesforce.com/us/developer/docs/apexcode/
salesforce_apex_language_reference.pdf
•  Appelman, Dan. Advanced Apex Programming. http://advancedapex.com
•  Douglas, Jeff. Blog. http://blog.jeffdouglas.com
•  Altman, Jesse. Blog. http://jessealtman.com
•  Bob Buzzard Blog. http://bobbuzzard.blogspot.be
•  Carlberg, Reid. Blog. http://reidcarlberg.com
Mary Scotton
Developer Evangelist
salesforce.com
@rockchick322004
Gonzalo Abruna
Developer & Analyst
4C Consulting (Belgium)
@GonzaloAbruna

Apex Algorithms: Tips and Tricks (Dreamforce 2014)

  • 1.
    Apex Algorithms: Tips& Tricks Mary Scotton Developer Evangelist salesforce.com @rockchick322004 Gonzalo Abruna Developer & Analyst 4C Consulting (Belgium) @GonzaloAbruna
  • 2.
    Safe Harbor Safe harborstatement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
  • 3.
    Agenda •  Top CoderChallenge •  Optimize SOQL queries •  How to optimize an algorithm: tips & tricks •  Summary •  References •  Q&A
  • 4.
    Use to uce a video, A,etc. Use Case: Mother-Son Bowling Event Assign each attendee to 1 of 30 lanes, ordered by grade
  • 8.
    Place er or go in eaof ered ntally Gonzalo Abruna Developer & Analyst, 4C Consulting (Belgium)
  • 9.
    Optimize SOQL queries SOQLLimits •  100 SOQL queries per transaction (200 if transaction is asynchronous) •  50.000 rows retrieved by SOQL queries •  120 seconds maximum SOQL query run time
  • 10.
  • 11.
    Optimize SOQL queries Requirements:Sample Scenario •  Query all the Contacts that have worked for an Account, via join object •  For those Contacts, get all the Accounts they have worked for
  • 12.
    Optimize SOQL queries Solution#1 •  Upsides –  Easy to implement •  Downsides –  Many loops –  Many SOQLs –  Bad performance
  • 13.
    Optimize SOQL queries Solution#2 •  Upsides –  Less SOQL queries –  Less loops (important for complex algorithms) •  Downsides –  Not much better than Solution #1 –  SOQL Limit: “In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query. These types of queries have a limit of three times the number for top-level queries. The row counts from these relationship queries contribute to the row counts of the overall code execution. In addition to static SOQL statements, calls to the following methods count against the number of SOQL statements issued in a request.”
  • 14.
    Optimize SOQL queries Solution#3 •  Upsides –  The most efficient –  Less SOQL queries –  Less loops (important for complex algorithms) •  Downsides –  Data structures may be required to represent the data
  • 15.
    Representing the Data • Upsides –  Avoids unnecessary loops –  Direct access to the records –  Easier to handle than lists without key •  Downsides –  Be careful with null pointer exceptions and reference to null object –  Maps are not ordered Solution #3, Part 2: Using Map<Id, List<sObject>>
  • 16.
    How to Optimizean Algorithm •  Use Map<Id, sObject> in SOQL queries List<Account> listAccounts = [SELECT Id, Name FROM Account]; Map<Id, Account> mapAccounts = new Map<Id, Account>([SELECT Id, Name FROM Account]); •  Estimate how big your data is & test empty values scenario •  Avoid unnecessary loops: try to reuse loops without losing readability of code Top Tricks
  • 17.
    How to Optimizean Algorithm •  Put conditions in SOQL queries, not in if statements List<Account> listAccounts = [SELECT Id, Name, Type FROM Account]; for(Account acc : listAccounts){ if(acc.Type == ‘Prospect’){…} } VS List<Account> listAccounts = [SELECT Id, Name, Type FROM Account WHERE Type = ‘Prospect’]; Top Tricks
  • 18.
    How to Optimizean Algorithm •  Query only the fields that you need •  Try to avoid putting formula fields on a WHERE clause •  Parent-Child SOQL to avoid loops –  Example: get the three newest Contacts per Account Top Tricks
  • 19.
    Summary •  Every algorithmis different •  Think before coding •  Be aware of limits •  Readability of code is important •  Complex algorithms can be broken down into smaller and easier (divide & conquer) •  The place of an algorithm is critical
  • 20.
    References •  Developer blogshttps://developer.salesforce.com/blogs/ •  Force.com Apex developer guide. http://www.salesforce.com/us/developer/docs/apexcode/ salesforce_apex_language_reference.pdf •  Appelman, Dan. Advanced Apex Programming. http://advancedapex.com •  Douglas, Jeff. Blog. http://blog.jeffdouglas.com •  Altman, Jesse. Blog. http://jessealtman.com •  Bob Buzzard Blog. http://bobbuzzard.blogspot.be •  Carlberg, Reid. Blog. http://reidcarlberg.com
  • 21.
    Mary Scotton Developer Evangelist salesforce.com @rockchick322004 GonzaloAbruna Developer & Analyst 4C Consulting (Belgium) @GonzaloAbruna