SlideShare a Scribd company logo
1 of 61
Download to read offline
Performance Tuning for Visualforce
and Apex
John Tan, salesforce.com, @johntansfdc
Thomas Harris, salesforce.com
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.
Your company uses
Salesforce/Force.com …
You are a developer or
architect…
Your Visualforce pages and Apex
classes are slower than you’d
like…
You need to find and fix the
issues…
Agenda
1. Record lock contention
2. Building efficient queries
3. Batch Apex
4. Visualforce
5. Apex and CPU limit
6. Debugging Tips and Tricks
John C. Tan
Lead Member of Technical Staff
Customer Centric Engineering
@johntansfdc
Thomas Harris
Lead Member of Technical Staff
Customer Centric Engineering
Architect Core Resource page
• Featured content for architects
• Articles, papers, blog posts,
events
• Follow us on Twitter
Updated weekly!
http://developer.force.com/architect
Build On A Solid Foundation
1. Data model & queries
2. Then tune Apex
3. Then tune Visualforce
By a show of hands…
How many of you have gotten these errors?

UNABLE_TO_LOCK_ROW
Record Lock Contention / Data
Skew
Parent-Child Locking
Parent-Child Locking
▪ Insert of Contact requires locking the parent Account.
▪ Insert or Update of Event requires locking both the parent Contact and the parent
Account.
▪ Insert or Update of Task requires locking both the parent Contact and parent Account,
if the Task is marked as complete.
▪ Insert of Case requires locking the parent Contact and parent Account.
▪ In objects that are part of a master/detail relationship, inserts require locking the
master. Updates will also lock the master if a roll-up summary is present.
▪ In objects that are part of a lookup relationship where the lookup is set to Clear on
delete, inserts require locking the target lookup record. Updates will lock the target
lookup record if the value of target changes.
Parent implicit sharing
Access to Contact/Opportunity/Case = Read access to
parent Account

Account:
Universal
Containers
Contact:
Bob
Smith
Data skew impacts DML operations
Universal
Trigger/RSF
Containers

?
Bob
Smith

Fred
Green

Betty
Brown

…

300K
Contact

New
Contact
Result Of Longer Sharing Calculations
▪ DML operations run longer
▪ Concurrent Request Limit errors
▪ UNABLE_TO_LOCK_ROW errors
Key Takeaways
✓ Prevent parent-child data skews
✓ 10K or less children
✓ Public read/write sharing model = No sharing calculations
Building Efficient Queries
What is the Force.com query optimizer?
Generates the most efficient query based on:
▪ Statistics
▪ Indexes / Skinny Tables
▪ Sharing
Best practice: One+ selective filter per query
Selective filters: Four components
1. Filters - add filters to reduce data
2. Operators - avoid 2 inefficient filter operators
3. Thresholds - filter meets selectivity threshold (efficient to
use index)
4. Index Creation - index the filter field
Fields that often make good filters
▪ Date fields
▪ Picklists
▪ Fields with wide and even distribution of values
Non-deterministic formula fields aren’t good filters
Can’t index
For example:
▪ References related object
▪ CASE(MyUser__r.UserType__c,1,”Gold”,”Silver”)
▪ Create separate field and use trigger to populate

Force.com SOQL Best Practices: Nulls and Formula Fields
Avoid negative operators
Query for reciprocal values instead
✖ Status != 'closed'
✔ Status IN ('open', 'in progress')
Avoid filters with a leading % wildcard
CONTAINS or LIKE ‘%searchstring%’
✖ CONTAINS ('district') / LIKE '%district%'
✔ STARTS WITH ('district') / LIKE 'district%'
Standard fields with indexes
▪ Id
▪ Name
▪ OwnerId
▪ CreatedDate
▪ SystemModstamp
▪ RecordType
▪ Master-detail fields
▪ Lookup fields
Custom indexes
• Discover common filter conditions
• Determine selective fields in those conditions
• Request custom indexes
Standard index selectivity threshold
A standard index is selective if it returns:
▪ < 30% of the first 1 million records
▪ < 15% of returned records after the first 1 million records
▪ No more than 1 million records
Standard index selectivity threshold
SELECT Id FROM Account WHERE CreatedDate >
'2013-01-01' AND CreatedDate < '2013-11-01'
For 750,000 Account records
▪ < 30% of the first 1 million records
▪ 750,000 x .30 = 225,000
Standard index selectivity threshold
For 3,500,000 Account records
▪ < 30% of the first 1 million records
▪ < 15% of returned records after the first 1 million records
▪ (1,000,000 x .30) + (2,500,000 x .15) = 675,000
Standard index selectivity threshold
Over 5,600,000 Account records
▪ No more than 1 million records
▪ 1,000,000
Custom index selectivity threshold
A custom index is selective if it returns:
▪ < 10% of the first 1 million records
▪ < 5% of returned records after the first 1 million records
▪ No more than 333,333 records
A filter condition is selective when …
… it uses an optimizable operator
… it meets the selectivity threshold
… selective fields have indexes
AND conditions
WHERE FirstName__c = 'Jane' AND LastName__c = 'Doe' AND
City__c = 'San Francisco'
Step 1 – Allow each index to still be considered if they return < 2X selectivity
threshold
Step 2 – INTERSECTION of all indexes must meet *selectivity threshold
Step 3 – Use composite index join to drive query
*If all indexes are standard indexes, use standard index selectivity threshold. Otherwise, use the custom index selectivity
threshold
AND conditions
Composite index join – MyUser object 100,000 total records
AND conditions
Composite index join – MyUser object 100,000 total records
2-column index
For this simple example, it makes more sense to have Customer Support create a 2-column index.
OR conditions
WHERE FirstName__c = 'Jane' OR LastName__c = 'Doe' OR
City__c = 'San Francisco'
Step 1 – Each field must be indexed and meet selectivity threshold
Step 2 – UNION of all the indexes must meet *selectivity threshold
Step 3 – Use union to drive query
*If all indexes are standard indexes, use standard index selectivity threshold. Otherwise, use the custom index selectivity
threshold
OR conditions
Union - MyUser object 100,000 total records
Tell me more…
Webinar: Inside the Force.com Query Optimizer
Key takeaways
✓ Queries should contain at least one selective filter
✓ A filter is selective if…
✓ the field is indexed
✓ the filter does not use an inefficient operator
✓ the filter meets the selectivity theshold
Batch Apex
Batch Apex
▪ The most common performance issue in Batch Apex is poor
performing queries in the start() method.
▪ Make sure you are using a selective filter in the start method.
Batch Apex start() method
▪ Suppose you have 5M records in Account. You want to process the
80% of those records represented by this query:
• SELECT Id FROM Account WHERE Rating__c IN
('Excellent','Good','Moderate')

▪ As an alternative, use this query in the start() method:
• SELECT Id FROM Account

▪ Filter out the unwanted records in the execute() method.
Batch Apex start() method example
global Database.QueryLocator<SObject> start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Account');
}
global void execute(Database.BatchableContext bc, List<Account> scope) {
List<Account> actualScope = [SELECT Id, Name, Description FROM Account
WHERE Rating__c IN
('Excellent','Good','Moderate’)
AND Id IN :scope];
for(Account acc : actualScope) { /* do something */ }
}
Visualforce
Visualforce
▪ In general, follow SOQL and Apex best practices.
▪ Visualforce-specific issues tend to be caused by complex pages with
large numbers of components, which in turn have a very large view
state.
Visualforce
▪ Techniques to reduce view state overhead:
• Filter and paginate results.
• Use the transient keyword
• Simplify the component hierarchy on the page.
• Use Javascript Remoting.
Apex and CPU Limits
Apex CPU Limits
▪ In Winter ‘14 Apex now has a CPU time limit rather than a
script statement limit.
▪ In general existing Apex code will be well under this limit.
▪ There are two main pitfalls to avoid that can use up large
amounts of CPU time with a low number of script
statements.
Apex CPU usage pitfalls
▪ String concatenation: doing large numbers of “+” operations with large
strings.
• Example:
String html = “<html>”;
html += “<body>”
html += …
• Avoid building huge strings this way using Apex.
• Use System.JSON and System.XmlStreamWriter if you need to build JSON or
XML output.

▪ Running complex regular expressions on large strings.
Debugging Tips and Tricks
Troubleshooting Methodology
▪ In general it’s a good idea to measure performance in the
browser first.
• Chrome Developer Tools is excellent for this.

▪ Once you know the problem is on the server-side, use the
Developer Console to dig in further.
• Check the usual suspects first:
– SOQL
– Callouts
Apex Debug Levels
▪ When troubleshooting performance issues, the default log
levels can generate a lot of noise.
▪ Set the log levels for everything to INFO initially, raise as
necessary.
• Go to Debug > Change Log Levels in the Developer Console to do this.
Working With Support
▪ Support can help with SOQL performance issues and can
create 1-column and 2-column custom indexes.
• Open a case and specify the organization ID, user ID, SOQL and bind
variables.

▪ For record locking issues, specify the organization ID, time
frame where the issue happened, and the IDs of affected
records if possible.
Summary
Key Takeaways
✓ Prevent parent-child data skews
✓ Queries should contain at least one selective filter
✓ Most common issue is performance of the start() method
SOQL
✓ Reduce view state in your Visualforce pages
We want to hear
from YOU!
Please take a moment to complete our
session survey
Surveys can be found in the “My Agenda”
portion of the Dreamforce app
Performance Tuning for Visualforce and Apex

More Related Content

What's hot

All About Test Class in #Salesforce
All About Test Class in #SalesforceAll About Test Class in #Salesforce
All About Test Class in #SalesforceAmit Singh
 
Real Time Integration with Salesforce Platform Events
Real Time Integration with Salesforce Platform EventsReal Time Integration with Salesforce Platform Events
Real Time Integration with Salesforce Platform EventsSalesforce Developers
 
Replicate Salesforce Data in Real Time with Change Data Capture
Replicate Salesforce Data in Real Time with Change Data CaptureReplicate Salesforce Data in Real Time with Change Data Capture
Replicate Salesforce Data in Real Time with Change Data CaptureSalesforce Developers
 
Salesforce Service Cloud
Salesforce Service CloudSalesforce Service Cloud
Salesforce Service Cloudsharad soni
 
Test Design and Automation for REST API
Test Design and Automation for REST APITest Design and Automation for REST API
Test Design and Automation for REST APIIvan Katunou
 
Basic interview questions for manual testing
Basic interview questions for manual testingBasic interview questions for manual testing
Basic interview questions for manual testingJYOTI RANJAN PAL
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionDionatan default
 
Flow in Salesforce
Flow in SalesforceFlow in Salesforce
Flow in Salesforcevikas singh
 
Getting Started With Apex REST Services
Getting Started With Apex REST ServicesGetting Started With Apex REST Services
Getting Started With Apex REST ServicesSalesforce Developers
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with CypressYong Shean Chong
 
API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)Peter Thomas
 
Approval Process in Salesforce
Approval Process in SalesforceApproval Process in Salesforce
Approval Process in SalesforceCloudTech 
 
TESTING LIFE CYCLE PPT
TESTING LIFE CYCLE PPTTESTING LIFE CYCLE PPT
TESTING LIFE CYCLE PPTsuhasreddy1
 

What's hot (20)

All About Test Class in #Salesforce
All About Test Class in #SalesforceAll About Test Class in #Salesforce
All About Test Class in #Salesforce
 
Real Time Integration with Salesforce Platform Events
Real Time Integration with Salesforce Platform EventsReal Time Integration with Salesforce Platform Events
Real Time Integration with Salesforce Platform Events
 
Salesforce asynchronous apex
Salesforce asynchronous apexSalesforce asynchronous apex
Salesforce asynchronous apex
 
Replicate Salesforce Data in Real Time with Change Data Capture
Replicate Salesforce Data in Real Time with Change Data CaptureReplicate Salesforce Data in Real Time with Change Data Capture
Replicate Salesforce Data in Real Time with Change Data Capture
 
Migrating To Lightning
Migrating To LightningMigrating To Lightning
Migrating To Lightning
 
Introduction to Apex Triggers
Introduction to Apex TriggersIntroduction to Apex Triggers
Introduction to Apex Triggers
 
Salesforce Service Cloud
Salesforce Service CloudSalesforce Service Cloud
Salesforce Service Cloud
 
Introduction to Apex for Developers
Introduction to Apex for DevelopersIntroduction to Apex for Developers
Introduction to Apex for Developers
 
Test Design and Automation for REST API
Test Design and Automation for REST APITest Design and Automation for REST API
Test Design and Automation for REST API
 
Basic interview questions for manual testing
Basic interview questions for manual testingBasic interview questions for manual testing
Basic interview questions for manual testing
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in Action
 
JMeter
JMeterJMeter
JMeter
 
Flow in Salesforce
Flow in SalesforceFlow in Salesforce
Flow in Salesforce
 
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang MinhTest Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
 
Getting Started With Apex REST Services
Getting Started With Apex REST ServicesGetting Started With Apex REST Services
Getting Started With Apex REST Services
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with Cypress
 
API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)
 
Approval Process in Salesforce
Approval Process in SalesforceApproval Process in Salesforce
Approval Process in Salesforce
 
Approval process
Approval processApproval process
Approval process
 
TESTING LIFE CYCLE PPT
TESTING LIFE CYCLE PPTTESTING LIFE CYCLE PPT
TESTING LIFE CYCLE PPT
 

Similar to Performance Tuning for Visualforce and Apex

The Need for Speed: Building Reports That Fly
The Need for Speed: Building Reports That FlyThe Need for Speed: Building Reports That Fly
The Need for Speed: Building Reports That FlySalesforce Developers
 
Performance Tuning for Visualforce and Apex
Performance Tuning for Visualforce and ApexPerformance Tuning for Visualforce and Apex
Performance Tuning for Visualforce and ApexSalesforce Developers
 
Apex Algorithms: Tips and Tricks (Dreamforce 2014)
Apex Algorithms: Tips and Tricks (Dreamforce 2014)Apex Algorithms: Tips and Tricks (Dreamforce 2014)
Apex Algorithms: Tips and Tricks (Dreamforce 2014)Mary Scotton
 
Follow the evidence: Troubleshooting Performance Issues
Follow the evidence:  Troubleshooting Performance IssuesFollow the evidence:  Troubleshooting Performance Issues
Follow the evidence: Troubleshooting Performance IssuesSalesforce Developers
 
Avoid Growing Pains: Scale Your App for the Enterprise (October 14, 2014)
Avoid Growing Pains: Scale Your App for the Enterprise (October 14, 2014)Avoid Growing Pains: Scale Your App for the Enterprise (October 14, 2014)
Avoid Growing Pains: Scale Your App for the Enterprise (October 14, 2014)Salesforce Partners
 
Become a Formula Ninja
Become a Formula NinjaBecome a Formula Ninja
Become a Formula NinjaConfigero
 
Analytic Snapshots: Common Use Cases that Everyone Can Utilize (Dreamforce 2...
Analytic Snapshots:  Common Use Cases that Everyone Can Utilize (Dreamforce 2...Analytic Snapshots:  Common Use Cases that Everyone Can Utilize (Dreamforce 2...
Analytic Snapshots: Common Use Cases that Everyone Can Utilize (Dreamforce 2...Rhonda Ross
 
Replicating One Billion Records with Minimal API Usage
Replicating One Billion Records with Minimal API UsageReplicating One Billion Records with Minimal API Usage
Replicating One Billion Records with Minimal API UsageSalesforce Developers
 
Mbf2 salesforce webinar 2
Mbf2 salesforce webinar 2Mbf2 salesforce webinar 2
Mbf2 salesforce webinar 2BeMyApp
 
A G S006 Little 091807
A G S006  Little 091807A G S006  Little 091807
A G S006 Little 091807Dreamforce07
 
Aan009 Contreras 091907
Aan009 Contreras 091907Aan009 Contreras 091907
Aan009 Contreras 091907Dreamforce07
 
Salesforce shield &amp; summer 20 release
Salesforce shield &amp; summer 20 releaseSalesforce shield &amp; summer 20 release
Salesforce shield &amp; summer 20 releaseDevendra Sawant
 
Looking under the hood of your org with eclipse
Looking under the hood of your org with eclipseLooking under the hood of your org with eclipse
Looking under the hood of your org with eclipseJamie Buck-Tomek
 
Data Design Tips for Developing Robust Apps on Force.com
Data Design Tips for Developing Robust Apps on Force.comData Design Tips for Developing Robust Apps on Force.com
Data Design Tips for Developing Robust Apps on Force.comSalesforce Developers
 
Designing Custom REST and SOAP Interfaces on Force.com
Designing Custom REST and SOAP Interfaces on Force.comDesigning Custom REST and SOAP Interfaces on Force.com
Designing Custom REST and SOAP Interfaces on Force.comSalesforce Developers
 
Best Practices for Team Development in a Single Org
Best Practices for Team Development in a Single OrgBest Practices for Team Development in a Single Org
Best Practices for Team Development in a Single OrgSalesforce Developers
 
Get ready for your platform developer i certification webinar
Get ready for your platform developer i certification   webinarGet ready for your platform developer i certification   webinar
Get ready for your platform developer i certification webinarJackGuo20
 

Similar to Performance Tuning for Visualforce and Apex (20)

The Need for Speed: Building Reports That Fly
The Need for Speed: Building Reports That FlyThe Need for Speed: Building Reports That Fly
The Need for Speed: Building Reports That Fly
 
Performance Tuning for Visualforce and Apex
Performance Tuning for Visualforce and ApexPerformance Tuning for Visualforce and Apex
Performance Tuning for Visualforce and Apex
 
Building Reports That Fly
Building Reports That FlyBuilding Reports That Fly
Building Reports That Fly
 
Apex Algorithms: Tips and Tricks (Dreamforce 2014)
Apex Algorithms: Tips and Tricks (Dreamforce 2014)Apex Algorithms: Tips and Tricks (Dreamforce 2014)
Apex Algorithms: Tips and Tricks (Dreamforce 2014)
 
Df12 Performance Tuning
Df12 Performance TuningDf12 Performance Tuning
Df12 Performance Tuning
 
Follow the evidence: Troubleshooting Performance Issues
Follow the evidence:  Troubleshooting Performance IssuesFollow the evidence:  Troubleshooting Performance Issues
Follow the evidence: Troubleshooting Performance Issues
 
Avoid Growing Pains: Scale Your App for the Enterprise (October 14, 2014)
Avoid Growing Pains: Scale Your App for the Enterprise (October 14, 2014)Avoid Growing Pains: Scale Your App for the Enterprise (October 14, 2014)
Avoid Growing Pains: Scale Your App for the Enterprise (October 14, 2014)
 
Become a Formula Ninja
Become a Formula NinjaBecome a Formula Ninja
Become a Formula Ninja
 
Analytic Snapshots: Common Use Cases that Everyone Can Utilize (Dreamforce 2...
Analytic Snapshots:  Common Use Cases that Everyone Can Utilize (Dreamforce 2...Analytic Snapshots:  Common Use Cases that Everyone Can Utilize (Dreamforce 2...
Analytic Snapshots: Common Use Cases that Everyone Can Utilize (Dreamforce 2...
 
Replicating One Billion Records with Minimal API Usage
Replicating One Billion Records with Minimal API UsageReplicating One Billion Records with Minimal API Usage
Replicating One Billion Records with Minimal API Usage
 
Mbf2 salesforce webinar 2
Mbf2 salesforce webinar 2Mbf2 salesforce webinar 2
Mbf2 salesforce webinar 2
 
A G S006 Little 091807
A G S006  Little 091807A G S006  Little 091807
A G S006 Little 091807
 
Large Data Management Strategies
Large Data Management StrategiesLarge Data Management Strategies
Large Data Management Strategies
 
Aan009 Contreras 091907
Aan009 Contreras 091907Aan009 Contreras 091907
Aan009 Contreras 091907
 
Salesforce shield &amp; summer 20 release
Salesforce shield &amp; summer 20 releaseSalesforce shield &amp; summer 20 release
Salesforce shield &amp; summer 20 release
 
Looking under the hood of your org with eclipse
Looking under the hood of your org with eclipseLooking under the hood of your org with eclipse
Looking under the hood of your org with eclipse
 
Data Design Tips for Developing Robust Apps on Force.com
Data Design Tips for Developing Robust Apps on Force.comData Design Tips for Developing Robust Apps on Force.com
Data Design Tips for Developing Robust Apps on Force.com
 
Designing Custom REST and SOAP Interfaces on Force.com
Designing Custom REST and SOAP Interfaces on Force.comDesigning Custom REST and SOAP Interfaces on Force.com
Designing Custom REST and SOAP Interfaces on Force.com
 
Best Practices for Team Development in a Single Org
Best Practices for Team Development in a Single OrgBest Practices for Team Development in a Single Org
Best Practices for Team Development in a Single Org
 
Get ready for your platform developer i certification webinar
Get ready for your platform developer i certification   webinarGet ready for your platform developer i certification   webinar
Get ready for your platform developer i certification webinar
 

More from Salesforce Developers

Sample Gallery: Reference Code and Best Practices for Salesforce Developers
Sample Gallery: Reference Code and Best Practices for Salesforce DevelopersSample Gallery: Reference Code and Best Practices for Salesforce Developers
Sample Gallery: Reference Code and Best Practices for Salesforce DevelopersSalesforce Developers
 
Maximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component PerformanceMaximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component PerformanceSalesforce Developers
 
Local development with Open Source Base Components
Local development with Open Source Base ComponentsLocal development with Open Source Base Components
Local development with Open Source Base ComponentsSalesforce Developers
 
TrailheaDX India : Developer Highlights
TrailheaDX India : Developer HighlightsTrailheaDX India : Developer Highlights
TrailheaDX India : Developer HighlightsSalesforce Developers
 
Why developers shouldn’t miss TrailheaDX India
Why developers shouldn’t miss TrailheaDX IndiaWhy developers shouldn’t miss TrailheaDX India
Why developers shouldn’t miss TrailheaDX IndiaSalesforce Developers
 
CodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Build Lightning Web Components faster with Local DevelopmentCodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Build Lightning Web Components faster with Local DevelopmentSalesforce Developers
 
CodeLive: Converting Aura Components to Lightning Web Components
CodeLive: Converting Aura Components to Lightning Web ComponentsCodeLive: Converting Aura Components to Lightning Web Components
CodeLive: Converting Aura Components to Lightning Web ComponentsSalesforce Developers
 
Enterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web ComponentsEnterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web ComponentsSalesforce Developers
 
TrailheaDX and Summer '19: Developer Highlights
TrailheaDX and Summer '19: Developer HighlightsTrailheaDX and Summer '19: Developer Highlights
TrailheaDX and Summer '19: Developer HighlightsSalesforce Developers
 
Lightning web components - Episode 4 : Security and Testing
Lightning web components  - Episode 4 : Security and TestingLightning web components  - Episode 4 : Security and Testing
Lightning web components - Episode 4 : Security and TestingSalesforce Developers
 
LWC Episode 3- Component Communication and Aura Interoperability
LWC Episode 3- Component Communication and Aura InteroperabilityLWC Episode 3- Component Communication and Aura Interoperability
LWC Episode 3- Component Communication and Aura InteroperabilitySalesforce Developers
 
Lightning web components episode 2- work with salesforce data
Lightning web components   episode 2- work with salesforce dataLightning web components   episode 2- work with salesforce data
Lightning web components episode 2- work with salesforce dataSalesforce Developers
 
Lightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionLightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionSalesforce Developers
 
Migrating CPQ to Advanced Calculator and JSQCP
Migrating CPQ to Advanced Calculator and JSQCPMigrating CPQ to Advanced Calculator and JSQCP
Migrating CPQ to Advanced Calculator and JSQCPSalesforce Developers
 
Scale with Large Data Volumes and Big Objects in Salesforce
Scale with Large Data Volumes and Big Objects in SalesforceScale with Large Data Volumes and Big Objects in Salesforce
Scale with Large Data Volumes and Big Objects in SalesforceSalesforce Developers
 
Modern Development with Salesforce DX
Modern Development with Salesforce DXModern Development with Salesforce DX
Modern Development with Salesforce DXSalesforce Developers
 
Integrate CMS Content Into Lightning Communities with CMS Connect
Integrate CMS Content Into Lightning Communities with CMS ConnectIntegrate CMS Content Into Lightning Communities with CMS Connect
Integrate CMS Content Into Lightning Communities with CMS ConnectSalesforce Developers
 

More from Salesforce Developers (20)

Sample Gallery: Reference Code and Best Practices for Salesforce Developers
Sample Gallery: Reference Code and Best Practices for Salesforce DevelopersSample Gallery: Reference Code and Best Practices for Salesforce Developers
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
 
Maximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component PerformanceMaximizing Salesforce Lightning Experience and Lightning Component Performance
Maximizing Salesforce Lightning Experience and Lightning Component Performance
 
Local development with Open Source Base Components
Local development with Open Source Base ComponentsLocal development with Open Source Base Components
Local development with Open Source Base Components
 
TrailheaDX India : Developer Highlights
TrailheaDX India : Developer HighlightsTrailheaDX India : Developer Highlights
TrailheaDX India : Developer Highlights
 
Why developers shouldn’t miss TrailheaDX India
Why developers shouldn’t miss TrailheaDX IndiaWhy developers shouldn’t miss TrailheaDX India
Why developers shouldn’t miss TrailheaDX India
 
CodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Build Lightning Web Components faster with Local DevelopmentCodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Build Lightning Web Components faster with Local Development
 
CodeLive: Converting Aura Components to Lightning Web Components
CodeLive: Converting Aura Components to Lightning Web ComponentsCodeLive: Converting Aura Components to Lightning Web Components
CodeLive: Converting Aura Components to Lightning Web Components
 
Enterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web ComponentsEnterprise-grade UI with open source Lightning Web Components
Enterprise-grade UI with open source Lightning Web Components
 
TrailheaDX and Summer '19: Developer Highlights
TrailheaDX and Summer '19: Developer HighlightsTrailheaDX and Summer '19: Developer Highlights
TrailheaDX and Summer '19: Developer Highlights
 
Live coding with LWC
Live coding with LWCLive coding with LWC
Live coding with LWC
 
Lightning web components - Episode 4 : Security and Testing
Lightning web components  - Episode 4 : Security and TestingLightning web components  - Episode 4 : Security and Testing
Lightning web components - Episode 4 : Security and Testing
 
LWC Episode 3- Component Communication and Aura Interoperability
LWC Episode 3- Component Communication and Aura InteroperabilityLWC Episode 3- Component Communication and Aura Interoperability
LWC Episode 3- Component Communication and Aura Interoperability
 
Lightning web components episode 2- work with salesforce data
Lightning web components   episode 2- work with salesforce dataLightning web components   episode 2- work with salesforce data
Lightning web components episode 2- work with salesforce data
 
Lightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionLightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An Introduction
 
Migrating CPQ to Advanced Calculator and JSQCP
Migrating CPQ to Advanced Calculator and JSQCPMigrating CPQ to Advanced Calculator and JSQCP
Migrating CPQ to Advanced Calculator and JSQCP
 
Scale with Large Data Volumes and Big Objects in Salesforce
Scale with Large Data Volumes and Big Objects in SalesforceScale with Large Data Volumes and Big Objects in Salesforce
Scale with Large Data Volumes and Big Objects in Salesforce
 
Modern Development with Salesforce DX
Modern Development with Salesforce DXModern Development with Salesforce DX
Modern Development with Salesforce DX
 
Get Into Lightning Flow Development
Get Into Lightning Flow DevelopmentGet Into Lightning Flow Development
Get Into Lightning Flow Development
 
Integrate CMS Content Into Lightning Communities with CMS Connect
Integrate CMS Content Into Lightning Communities with CMS ConnectIntegrate CMS Content Into Lightning Communities with CMS Connect
Integrate CMS Content Into Lightning Communities with CMS Connect
 
Introduction to MuleSoft
Introduction to MuleSoftIntroduction to MuleSoft
Introduction to MuleSoft
 

Recently uploaded

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Recently uploaded (20)

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Performance Tuning for Visualforce and Apex

  • 1. Performance Tuning for Visualforce and Apex John Tan, salesforce.com, @johntansfdc Thomas Harris, salesforce.com
  • 2. 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.
  • 4. You are a developer or architect…
  • 5. Your Visualforce pages and Apex classes are slower than you’d like…
  • 6. You need to find and fix the issues…
  • 7. Agenda 1. Record lock contention 2. Building efficient queries 3. Batch Apex 4. Visualforce 5. Apex and CPU limit 6. Debugging Tips and Tricks
  • 8. John C. Tan Lead Member of Technical Staff Customer Centric Engineering @johntansfdc
  • 9. Thomas Harris Lead Member of Technical Staff Customer Centric Engineering
  • 10. Architect Core Resource page • Featured content for architects • Articles, papers, blog posts, events • Follow us on Twitter Updated weekly! http://developer.force.com/architect
  • 11. Build On A Solid Foundation 1. Data model & queries 2. Then tune Apex 3. Then tune Visualforce
  • 12. By a show of hands… How many of you have gotten these errors? UNABLE_TO_LOCK_ROW
  • 13. Record Lock Contention / Data Skew
  • 15. Parent-Child Locking ▪ Insert of Contact requires locking the parent Account. ▪ Insert or Update of Event requires locking both the parent Contact and the parent Account. ▪ Insert or Update of Task requires locking both the parent Contact and parent Account, if the Task is marked as complete. ▪ Insert of Case requires locking the parent Contact and parent Account. ▪ In objects that are part of a master/detail relationship, inserts require locking the master. Updates will also lock the master if a roll-up summary is present. ▪ In objects that are part of a lookup relationship where the lookup is set to Clear on delete, inserts require locking the target lookup record. Updates will lock the target lookup record if the value of target changes.
  • 16. Parent implicit sharing Access to Contact/Opportunity/Case = Read access to parent Account Account: Universal Containers Contact: Bob Smith
  • 17. Data skew impacts DML operations Universal Trigger/RSF Containers ? Bob Smith Fred Green Betty Brown … 300K Contact New Contact
  • 18. Result Of Longer Sharing Calculations ▪ DML operations run longer ▪ Concurrent Request Limit errors ▪ UNABLE_TO_LOCK_ROW errors
  • 19. Key Takeaways ✓ Prevent parent-child data skews ✓ 10K or less children ✓ Public read/write sharing model = No sharing calculations
  • 21. What is the Force.com query optimizer? Generates the most efficient query based on: ▪ Statistics ▪ Indexes / Skinny Tables ▪ Sharing
  • 22. Best practice: One+ selective filter per query
  • 23. Selective filters: Four components 1. Filters - add filters to reduce data 2. Operators - avoid 2 inefficient filter operators 3. Thresholds - filter meets selectivity threshold (efficient to use index) 4. Index Creation - index the filter field
  • 24. Fields that often make good filters ▪ Date fields ▪ Picklists ▪ Fields with wide and even distribution of values
  • 25. Non-deterministic formula fields aren’t good filters Can’t index For example: ▪ References related object ▪ CASE(MyUser__r.UserType__c,1,”Gold”,”Silver”) ▪ Create separate field and use trigger to populate Force.com SOQL Best Practices: Nulls and Formula Fields
  • 26. Avoid negative operators Query for reciprocal values instead ✖ Status != 'closed' ✔ Status IN ('open', 'in progress')
  • 27. Avoid filters with a leading % wildcard CONTAINS or LIKE ‘%searchstring%’ ✖ CONTAINS ('district') / LIKE '%district%' ✔ STARTS WITH ('district') / LIKE 'district%'
  • 28. Standard fields with indexes ▪ Id ▪ Name ▪ OwnerId ▪ CreatedDate ▪ SystemModstamp ▪ RecordType ▪ Master-detail fields ▪ Lookup fields
  • 29. Custom indexes • Discover common filter conditions • Determine selective fields in those conditions • Request custom indexes
  • 30. Standard index selectivity threshold A standard index is selective if it returns: ▪ < 30% of the first 1 million records ▪ < 15% of returned records after the first 1 million records ▪ No more than 1 million records
  • 31. Standard index selectivity threshold SELECT Id FROM Account WHERE CreatedDate > '2013-01-01' AND CreatedDate < '2013-11-01' For 750,000 Account records ▪ < 30% of the first 1 million records ▪ 750,000 x .30 = 225,000
  • 32. Standard index selectivity threshold For 3,500,000 Account records ▪ < 30% of the first 1 million records ▪ < 15% of returned records after the first 1 million records ▪ (1,000,000 x .30) + (2,500,000 x .15) = 675,000
  • 33. Standard index selectivity threshold Over 5,600,000 Account records ▪ No more than 1 million records ▪ 1,000,000
  • 34. Custom index selectivity threshold A custom index is selective if it returns: ▪ < 10% of the first 1 million records ▪ < 5% of returned records after the first 1 million records ▪ No more than 333,333 records
  • 35. A filter condition is selective when … … it uses an optimizable operator … it meets the selectivity threshold … selective fields have indexes
  • 36. AND conditions WHERE FirstName__c = 'Jane' AND LastName__c = 'Doe' AND City__c = 'San Francisco' Step 1 – Allow each index to still be considered if they return < 2X selectivity threshold Step 2 – INTERSECTION of all indexes must meet *selectivity threshold Step 3 – Use composite index join to drive query *If all indexes are standard indexes, use standard index selectivity threshold. Otherwise, use the custom index selectivity threshold
  • 37. AND conditions Composite index join – MyUser object 100,000 total records
  • 38. AND conditions Composite index join – MyUser object 100,000 total records
  • 39. 2-column index For this simple example, it makes more sense to have Customer Support create a 2-column index.
  • 40. OR conditions WHERE FirstName__c = 'Jane' OR LastName__c = 'Doe' OR City__c = 'San Francisco' Step 1 – Each field must be indexed and meet selectivity threshold Step 2 – UNION of all the indexes must meet *selectivity threshold Step 3 – Use union to drive query *If all indexes are standard indexes, use standard index selectivity threshold. Otherwise, use the custom index selectivity threshold
  • 41. OR conditions Union - MyUser object 100,000 total records
  • 42. Tell me more… Webinar: Inside the Force.com Query Optimizer
  • 43. Key takeaways ✓ Queries should contain at least one selective filter ✓ A filter is selective if… ✓ the field is indexed ✓ the filter does not use an inefficient operator ✓ the filter meets the selectivity theshold
  • 45. Batch Apex ▪ The most common performance issue in Batch Apex is poor performing queries in the start() method. ▪ Make sure you are using a selective filter in the start method.
  • 46. Batch Apex start() method ▪ Suppose you have 5M records in Account. You want to process the 80% of those records represented by this query: • SELECT Id FROM Account WHERE Rating__c IN ('Excellent','Good','Moderate') ▪ As an alternative, use this query in the start() method: • SELECT Id FROM Account ▪ Filter out the unwanted records in the execute() method.
  • 47. Batch Apex start() method example global Database.QueryLocator<SObject> start(Database.BatchableContext bc) { return Database.getQueryLocator('SELECT Id FROM Account'); } global void execute(Database.BatchableContext bc, List<Account> scope) { List<Account> actualScope = [SELECT Id, Name, Description FROM Account WHERE Rating__c IN ('Excellent','Good','Moderate’) AND Id IN :scope]; for(Account acc : actualScope) { /* do something */ } }
  • 49. Visualforce ▪ In general, follow SOQL and Apex best practices. ▪ Visualforce-specific issues tend to be caused by complex pages with large numbers of components, which in turn have a very large view state.
  • 50. Visualforce ▪ Techniques to reduce view state overhead: • Filter and paginate results. • Use the transient keyword • Simplify the component hierarchy on the page. • Use Javascript Remoting.
  • 51. Apex and CPU Limits
  • 52. Apex CPU Limits ▪ In Winter ‘14 Apex now has a CPU time limit rather than a script statement limit. ▪ In general existing Apex code will be well under this limit. ▪ There are two main pitfalls to avoid that can use up large amounts of CPU time with a low number of script statements.
  • 53. Apex CPU usage pitfalls ▪ String concatenation: doing large numbers of “+” operations with large strings. • Example: String html = “<html>”; html += “<body>” html += … • Avoid building huge strings this way using Apex. • Use System.JSON and System.XmlStreamWriter if you need to build JSON or XML output. ▪ Running complex regular expressions on large strings.
  • 55. Troubleshooting Methodology ▪ In general it’s a good idea to measure performance in the browser first. • Chrome Developer Tools is excellent for this. ▪ Once you know the problem is on the server-side, use the Developer Console to dig in further. • Check the usual suspects first: – SOQL – Callouts
  • 56. Apex Debug Levels ▪ When troubleshooting performance issues, the default log levels can generate a lot of noise. ▪ Set the log levels for everything to INFO initially, raise as necessary. • Go to Debug > Change Log Levels in the Developer Console to do this.
  • 57. Working With Support ▪ Support can help with SOQL performance issues and can create 1-column and 2-column custom indexes. • Open a case and specify the organization ID, user ID, SOQL and bind variables. ▪ For record locking issues, specify the organization ID, time frame where the issue happened, and the IDs of affected records if possible.
  • 59. Key Takeaways ✓ Prevent parent-child data skews ✓ Queries should contain at least one selective filter ✓ Most common issue is performance of the start() method SOQL ✓ Reduce view state in your Visualforce pages
  • 60. We want to hear from YOU! Please take a moment to complete our session survey Surveys can be found in the “My Agenda” portion of the Dreamforce app