SlideShare una empresa de Scribd logo
1 de 61
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Salesforce Sales Cloud: Best Practices to Win More Deals
Salesforce Sales Cloud: Best Practices to Win More DealsSalesforce Sales Cloud: Best Practices to Win More Deals
Salesforce Sales Cloud: Best Practices to Win More DealsCloud Analogy
 
Salesforce Security Model (Dmitry Goshko, Igor Haritonovich)
Salesforce Security Model (Dmitry Goshko, Igor Haritonovich)Salesforce Security Model (Dmitry Goshko, Igor Haritonovich)
Salesforce Security Model (Dmitry Goshko, Igor Haritonovich)Yury Bondarau
 
Tackling Salesforce Technical Debt
Tackling Salesforce Technical DebtTackling Salesforce Technical Debt
Tackling Salesforce Technical Debtpanayaofficial
 
Triggers and order of execution1
Triggers and order of execution1Triggers and order of execution1
Triggers and order of execution1Prabhakar Sharma
 
Planning Your Migration to the Lightning Experience
Planning Your Migration to the Lightning ExperiencePlanning Your Migration to the Lightning Experience
Planning Your Migration to the Lightning ExperienceShell Black
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best PracticesVivek Chawla
 
Einstein Analyticsによるユースケース別機能、実現例のご紹介(前編)〜Winter’18 新機能紹介を交えて
Einstein Analyticsによるユースケース別機能、実現例のご紹介(前編)〜Winter’18 新機能紹介を交えてEinstein Analyticsによるユースケース別機能、実現例のご紹介(前編)〜Winter’18 新機能紹介を交えて
Einstein Analyticsによるユースケース別機能、実現例のご紹介(前編)〜Winter’18 新機能紹介を交えてSalesforce Developers Japan
 
Reports and dashboards @salesforce
Reports and dashboards @salesforceReports and dashboards @salesforce
Reports and dashboards @salesforceKapil Kumar Patle
 
Automate All The Things with Flow
Automate All The Things with FlowAutomate All The Things with Flow
Automate All The Things with FlowSalesforce Admins
 
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
 
Ivan Gubynskyy Salesforce CRM and Platform Overview
Ivan Gubynskyy Salesforce CRM and Platform OverviewIvan Gubynskyy Salesforce CRM and Platform Overview
Ivan Gubynskyy Salesforce CRM and Platform OverviewLogeekNightUkraine
 
Getting started with Salesforce security
Getting started with Salesforce securityGetting started with Salesforce security
Getting started with Salesforce securitySalesforce Admins
 
Salesforce integration best practices columbus meetup
Salesforce integration best practices   columbus meetupSalesforce integration best practices   columbus meetup
Salesforce integration best practices columbus meetupMuleSoft Meetup
 
Big Data in e-Commerce
Big Data in e-CommerceBig Data in e-Commerce
Big Data in e-CommerceDivante
 
Apex enterprise patterns
Apex enterprise patternsApex enterprise patterns
Apex enterprise patternsAmit Jain
 

La actualidad más candente (20)

Salesforce Sales Cloud: Best Practices to Win More Deals
Salesforce Sales Cloud: Best Practices to Win More DealsSalesforce Sales Cloud: Best Practices to Win More Deals
Salesforce Sales Cloud: Best Practices to Win More Deals
 
Salesforce Security Model (Dmitry Goshko, Igor Haritonovich)
Salesforce Security Model (Dmitry Goshko, Igor Haritonovich)Salesforce Security Model (Dmitry Goshko, Igor Haritonovich)
Salesforce Security Model (Dmitry Goshko, Igor Haritonovich)
 
Tackling Salesforce Technical Debt
Tackling Salesforce Technical DebtTackling Salesforce Technical Debt
Tackling Salesforce Technical Debt
 
Triggers and order of execution1
Triggers and order of execution1Triggers and order of execution1
Triggers and order of execution1
 
Planning Your Migration to the Lightning Experience
Planning Your Migration to the Lightning ExperiencePlanning Your Migration to the Lightning Experience
Planning Your Migration to the Lightning Experience
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best Practices
 
Top Benefits of Salesforce in Business
Top Benefits of Salesforce in BusinessTop Benefits of Salesforce in Business
Top Benefits of Salesforce in Business
 
Exploring the Salesforce REST API
Exploring the Salesforce REST APIExploring the Salesforce REST API
Exploring the Salesforce REST API
 
Einstein Analyticsによるユースケース別機能、実現例のご紹介(前編)〜Winter’18 新機能紹介を交えて
Einstein Analyticsによるユースケース別機能、実現例のご紹介(前編)〜Winter’18 新機能紹介を交えてEinstein Analyticsによるユースケース別機能、実現例のご紹介(前編)〜Winter’18 新機能紹介を交えて
Einstein Analyticsによるユースケース別機能、実現例のご紹介(前編)〜Winter’18 新機能紹介を交えて
 
Reports and dashboards @salesforce
Reports and dashboards @salesforceReports and dashboards @salesforce
Reports and dashboards @salesforce
 
Automate All The Things with Flow
Automate All The Things with FlowAutomate All The Things with Flow
Automate All The Things with Flow
 
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
 
Governor limits
Governor limitsGovernor limits
Governor limits
 
Einstein Analytics
Einstein Analytics Einstein Analytics
Einstein Analytics
 
Ivan Gubynskyy Salesforce CRM and Platform Overview
Ivan Gubynskyy Salesforce CRM and Platform OverviewIvan Gubynskyy Salesforce CRM and Platform Overview
Ivan Gubynskyy Salesforce CRM and Platform Overview
 
Getting started with Salesforce security
Getting started with Salesforce securityGetting started with Salesforce security
Getting started with Salesforce security
 
Salesforce integration best practices columbus meetup
Salesforce integration best practices   columbus meetupSalesforce integration best practices   columbus meetup
Salesforce integration best practices columbus meetup
 
Big Data in e-Commerce
Big Data in e-CommerceBig Data in e-Commerce
Big Data in e-Commerce
 
Apex enterprise patterns
Apex enterprise patternsApex enterprise patterns
Apex enterprise patterns
 
Trialforce
Trialforce Trialforce
Trialforce
 

Similar a 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 a 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
 

Más de 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
 
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
 
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
 
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
 

Más de 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
 
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
 
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
 
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
 

Último

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Último (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

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