Performance Tuning for Visualforce and Apex

1,444 views
1,241 views

Published on

Visualforce and Apex allow developers to extend the Force.com platform and build custom applications. There are, however, some common themes in customer implementations that can adversely affect performance. Join us to learn best practices and debugging techniques for tuning performance of your Apex and Visualforce code.

Published in: Technology, Business
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,444
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
54
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Performance Tuning for Visualforce and Apex

  1. 1. Performance Tuning for Visualforce and Apex John Tan, salesforce.com, @johntansfdc Thomas Harris, salesforce.com
  2. 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.
  3. 3. Your company uses Salesforce/Force.com …
  4. 4. You are a developer or architect…
  5. 5. Your Visualforce pages and Apex classes are slower than you’d like…
  6. 6. You need to find and fix the issues…
  7. 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. 8. John C. Tan Lead Member of Technical Staff Customer Centric Engineering @johntansfdc
  9. 9. Thomas Harris Lead Member of Technical Staff Customer Centric Engineering
  10. 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. 11. Build On A Solid Foundation 1. Data model & queries 2. Then tune Apex 3. Then tune Visualforce
  12. 12. By a show of hands… How many of you have gotten these errors? UNABLE_TO_LOCK_ROW
  13. 13. Record Lock Contention / Data Skew
  14. 14. Parent-Child Locking
  15. 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. 16. Parent implicit sharing Access to Contact/Opportunity/Case = Read access to parent Account Account: Universal Containers Contact: Bob Smith
  17. 17. Data skew impacts DML operations Universal Trigger/RSF Containers ? Bob Smith Fred Green Betty Brown … 300K Contact New Contact
  18. 18. Result Of Longer Sharing Calculations ▪ DML operations run longer ▪ Concurrent Request Limit errors ▪ UNABLE_TO_LOCK_ROW errors
  19. 19. Key Takeaways ✓ Prevent parent-child data skews ✓ 10K or less children ✓ Public read/write sharing model = No sharing calculations
  20. 20. Building Efficient Queries
  21. 21. What is the Force.com query optimizer? Generates the most efficient query based on: ▪ Statistics ▪ Indexes / Skinny Tables ▪ Sharing
  22. 22. Best practice: One+ selective filter per query
  23. 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. 24. Fields that often make good filters ▪ Date fields ▪ Picklists ▪ Fields with wide and even distribution of values
  25. 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. 26. Avoid negative operators Query for reciprocal values instead ✖ Status != 'closed' ✔ Status IN ('open', 'in progress')
  27. 27. Avoid filters with a leading % wildcard CONTAINS or LIKE ‘%searchstring%’ ✖ CONTAINS ('district') / LIKE '%district%' ✔ STARTS WITH ('district') / LIKE 'district%'
  28. 28. Standard fields with indexes ▪ Id ▪ Name ▪ OwnerId ▪ CreatedDate ▪ SystemModstamp ▪ RecordType ▪ Master-detail fields ▪ Lookup fields
  29. 29. Custom indexes • Discover common filter conditions • Determine selective fields in those conditions • Request custom indexes
  30. 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. 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. 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. 33. Standard index selectivity threshold Over 5,600,000 Account records ▪ No more than 1 million records ▪ 1,000,000
  34. 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. 35. A filter condition is selective when … … it uses an optimizable operator … it meets the selectivity threshold … selective fields have indexes
  36. 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. 37. AND conditions Composite index join – MyUser object 100,000 total records
  38. 38. AND conditions Composite index join – MyUser object 100,000 total records
  39. 39. 2-column index For this simple example, it makes more sense to have Customer Support create a 2-column index.
  40. 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. 41. OR conditions Union - MyUser object 100,000 total records
  42. 42. Tell me more… Webinar: Inside the Force.com Query Optimizer
  43. 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
  44. 44. Batch Apex
  45. 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. 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. 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 */ } }
  48. 48. Visualforce
  49. 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. 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. 51. Apex and CPU Limits
  52. 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. 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.
  54. 54. Debugging Tips and Tricks
  55. 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. 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. 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.
  58. 58. Summary
  59. 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. 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

×