SlideShare a Scribd company logo
1 of 6
NHibernate Performance Tuning

                   To: Development Team
                   By: Shahzad Sarwar
                   Dated: 1st April 2010
Table of Content



1Objective:...........................................................................................................................3
2Problem definition: ...........................................................................................................3
3Performance Tuning tips for NHibernate:.........................................................................3
1    Objective:
To study the tips/tricks/Guidelines related to performance tuning for NHibernate based application.



     2     Problem definition:
Any fool can start a software to build, but to make it live on client’s production environment as a living
legend is not easy task, it requires high end skills in Software Architecture. Performance is always a major
concerns, which contribute to failures of software projects.


OR Mapping is generally slower then direct ADO .Net connection. That is true for both nHibernate and
LINQ2SQL. Applications which have a lot of data centric operations are not suited for NHibernate in
general for OR Mapping. However application which have application centric operations or calculation
going on are best suited for NHibernate or OR Mapping.

So if you are making a Enterprise CRM Product, then NHibernate(OR mapping) is not a good choice
because of inherited performance issues. ( Because of heavy data centric operations)

If you are making a multi player online game or simulator, then NHibernate is a good choice because a few
data operations are required and more processing is required at application logic.

So think twice before starting a project and make good choice at the start of application and rest in peace
rest of your life….:)
Bad Architecture decisions cause trouble for whole development team and project.



     3    Performance Tuning tips for NHibernate:
After some googleing and reading online documentation, I have finalized, following list of 21 points
regarding performance tuning for a NHibernate application.



      3.1   NHibernate's SessionFactory is an expensive operation so a good strategy is to creates a
            Singleton which ensures that there is only ONE instance of SessionFactory in memory:
 public class NHibernateSessionManager
  {
      private readonly ISessionFactory _sessionFactory;


      public static readonly NHibernateSessionManager Instance = new NHibernateSessionManager();


      private NHibernateSessionManager()
      {
          if (_sessionFactory == null)
          {
System.Diagnostics.Debug.WriteLine("Factory was null - creating one");
                _sessionFactory = (new Configuration().Configure().BuildSessionFactory());
            }
        }


        public ISession GetSession()
        {
            return _sessionFactory.OpenSession();
        }


        public void Initialize()
        {
            ISession disposeMe = Instance.GetSession();
        }
    }

Then in your Global.Asax Application_Startup, you can initialize it:

protected void Application_Start()
{
    NHibernateSessionManager.Instance.Initialize();
}




        3.2       Fetching strategy is key to performance tuning in Nhibernate project. A fetching strategy is the
                  strategy NHibernate will use for retrieving associated objects if the application needs to
                  navigate the association.

            Two things are important: when is the association fetched, and how is it fetched (what SQL is used).

            Clearly understand and use following:

            Join fetching
            Select fetching
            Subselect fetching
            "Extra-lazy" collection fetching
            Batch fetching

            Also follow:
            Immediate fetching
            Lazy collection fetching
            Proxy fetching
Best tip is to analyze the trade off b/w eager loading vs lazy loading. It varies case of case for
  implementation.
3.3    Make read-only classes immutable.
3.4    Multi query is executed by concatenating the queries and sending the query to the database as a
       single string. This means that the database should support returning several result sets in a
       single query. At the moment this functionality is only enabled for Microsoft SQL Server and
       SQLite.


 IMultiQuery multiQuery = s.CreateMultiQuery()

   .Add(s.CreateQuery("from Item i where i.Id > ?")
          .SetInt32(0, 50).SetFirstResult(10))
   .Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
          .SetInt32(0, 50));
 IList results = multiQuery.List();
 IList items = (IList)results[0];

 long count = (long)((IList)results[1])[0];

3.5    Multi Criteria like Multi query allows to perform several criteria queries in a single round trip.

 IMultiCriteria multiCrit = s.CreateMultiCriteria()
   .Add(s.CreateCriteria(typeof(Item))
          .Add(Expression.Gt("Id", 50))
          .SetFirstResult(10))
   .Add(s.CreateCriteria(typeof(Item))
          .Add(Expression.Gt("Id", 50))
          .SetProject(Projections.RowCount()));
 IList results = multiCrit.List();
 IList items = (IList)results[0];

 long count = (long)((IList)results[1])[0];

3.6    NHibernate 1.2 supports batching SQL update commands (INSERT, UPDATE, DELETE) for
       SQL Server and .NET Framework 2.0 or above.Update batching is enabled by setting
       hibernate.adonet.batch_size to a non-zero value.

3.7    Most Important tip is to avoid looping b/w object collections , when conditional data fetching /
       manipulation is required. Looping b/w collection of large size can really hurt the performance.
       Use HQL to transform your conditions to Criterias that can really save you processing time.

       Lets take example of getting Voucher entities having voucher details collection with some
       conditions. So don’t traverse the collection of vouchers and voucher details, use HQL to fetch
       the required entities.

       System.Collections.IList list = null;
       NHibernate.ICriteria crit =
       Common.Common.Instance.GetSession.CreateCriteria(typeof(VoucherDetail),
       "VoucherDetail");
       crit.CreateCriteria("VoucherHead" ,"VH");
       crit.Add(NHibernate.Criterion.Expression.Eq("Account", objacc));
crit.Add(NHibernate.Criterion.Expression.Eq("VH.SupInvNo", InvNo));
            crit.Add(NHibernate.Criterion.Expression.Eq("SrNo", Convert.ToInt16(0)));
            crit.Add(NHibernate.Criterion.Expression.Not(NHibernate.Criterion.Expression.Eq("VH.Vouc
            herID", ID)));
                   crit.SetFetchMode("VoucherDetail", NHibernate.FetchMode.Eager);
                   crit.SetFetchMode("VoucherHead", NHibernate.FetchMode.Eager);
                   setFinancialYearCriteria(crit, typeof(VoucherDetail));
                   list = crit.List();

     3.8    Use SQL Profiler and NH Profiler to view the queries generated by OR Mapping.
     3.9    Use query plan to analyze the queries sent by nhibernate.
     3.10   Create good indexes on tables to get better results.
     3.11   Use “Database Engine Tuning Advisor” to get feedback from SQL Server regarding
            optimization.
     3.12    Best practices for DB normalization can really help to solve the slow down of application.
            Bad DB design really kills NHibernate speed.
     3.13   Using value type objects for your properties and components as opposed to reference types,
            when you have a choice, this will lower memory footprint.
     3.14   Consider your logging strategy for production (less verbose) and usually disable show_sql in
            production.
     3.15   When expensive data queries are envolved or there are limitations of OR Mapping coming up,
            it is better to use native SQL queries in NHibernate. That increases the performance of
            application.
     3.16   In case of extreme database centric operations, store procedures can also speed up the
            performance.
            string sql = "exec GetJobExpenseAccounts ";
            NHibernate.ISQLQuery qry= Common.Common.Instance.GetSession.CreateSQLQuery(sql);
     3.17   Avoid composite keys (exception legacy databases). Composite keys are problematic for
            database design as well as OR/M therefore avoid them. reference
     3.18   Remove any columns and properties that you will never or should never need or use.
     3.19   Have a good strategy for flushing and transaction management. Remember that if you commit
            a transaction that you do not need to flush the object. reference
     3.20   Enable 2nd level cache and have a strategy for using it for some of your classes. For details
            view manual here.
     3.21   Read Collection optimization tips in NHibernate documentation. For details view manual here.



References:
http://scottwhite.blogspot.com/2009/04/nhibernate-performance-tuning.html
http://www.codeproject.com/KB/database/NHibernate_Perf.aspx
http://www.codeproject.com/KB/database/NHibernate_Perf2.aspx
http://www.iamnotmyself.com/2008/07/02/NHibernateTestingThePerformanceUrbanLegend.aspx
http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx
http://www.objectreference.net/post/NHibernate-and-Execution-Plans.aspx
http://devlicio.us/blogs/billy_mccafferty/archive/2007/03/03/nhibernate-performance-tuning.aspx

More Related Content

What's hot

Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialSyed Shahul
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4soelinn
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Mule esb – connecting to ms sql db
Mule esb – connecting to ms sql dbMule esb – connecting to ms sql db
Mule esb – connecting to ms sql dbGunjan Deshmukh
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10minszmcartor
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateThorben Janssen
 
Core data orlando i os dev group
Core data   orlando i os dev groupCore data   orlando i os dev group
Core data orlando i os dev groupAndrew Kozlik
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)Markus Eisele
 
Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Fwdays
 

What's hot (18)

Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 
Core Data
Core DataCore Data
Core Data
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Mule esb – connecting to ms sql db
Mule esb – connecting to ms sql dbMule esb – connecting to ms sql db
Mule esb – connecting to ms sql db
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10mins
 
Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
 
Core data orlando i os dev group
Core data   orlando i os dev groupCore data   orlando i os dev group
Core data orlando i os dev group
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"
 
11-DWR-and-JQuery
11-DWR-and-JQuery11-DWR-and-JQuery
11-DWR-and-JQuery
 

Similar to To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hibernate Based Application

Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookiesMahmoudOHassouna
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
At the core you will have KUSTO
At the core you will have KUSTOAt the core you will have KUSTO
At the core you will have KUSTORiccardo Zamana
 
[2C2]PredictionIO
[2C2]PredictionIO[2C2]PredictionIO
[2C2]PredictionIONAVER D2
 
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...GITS Indonesia
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Sparkhound Inc.
 
123448572 all-in-one-informatica
123448572 all-in-one-informatica123448572 all-in-one-informatica
123448572 all-in-one-informaticahomeworkping9
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
Introduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalIntroduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalM Malai
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerMydbops
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jjJoe Jacob
 
Journey to Azure Sentinel
Journey to Azure SentinelJourney to Azure Sentinel
Journey to Azure SentinelCheah Eng Soon
 
Flavours - Classic/Technical BDD
Flavours - Classic/Technical BDDFlavours - Classic/Technical BDD
Flavours - Classic/Technical BDDDavid Harrison
 
127556030 bisp-informatica-question-collections
127556030 bisp-informatica-question-collections127556030 bisp-informatica-question-collections
127556030 bisp-informatica-question-collectionsAmit Sharma
 
Azure machine learning service
Azure machine learning serviceAzure machine learning service
Azure machine learning serviceRuth Yakubu
 
Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsUlf Wendel
 
Simplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data WarehouseSimplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data WarehouseFeatureByte
 

Similar to To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hibernate Based Application (20)

Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
At the core you will have KUSTO
At the core you will have KUSTOAt the core you will have KUSTO
At the core you will have KUSTO
 
[2C2]PredictionIO
[2C2]PredictionIO[2C2]PredictionIO
[2C2]PredictionIO
 
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
 
123448572 all-in-one-informatica
123448572 all-in-one-informatica123448572 all-in-one-informatica
123448572 all-in-one-informatica
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
Introduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-finalIntroduction to-mongo db-execution-plan-optimizer-final
Introduction to-mongo db-execution-plan-optimizer-final
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizer
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 
Journey to Azure Sentinel
Journey to Azure SentinelJourney to Azure Sentinel
Journey to Azure Sentinel
 
Flavours - Classic/Technical BDD
Flavours - Classic/Technical BDDFlavours - Classic/Technical BDD
Flavours - Classic/Technical BDD
 
127556030 bisp-informatica-question-collections
127556030 bisp-informatica-question-collections127556030 bisp-informatica-question-collections
127556030 bisp-informatica-question-collections
 
Azure machine learning service
Azure machine learning serviceAzure machine learning service
Azure machine learning service
 
Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIs
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Simplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data WarehouseSimplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data Warehouse
 

More from Shahzad

Srs sso-version-1.2-stable version-0
Srs sso-version-1.2-stable version-0Srs sso-version-1.2-stable version-0
Srs sso-version-1.2-stable version-0Shahzad
 
Srs sso-version-1.2-stable version
Srs sso-version-1.2-stable versionSrs sso-version-1.2-stable version
Srs sso-version-1.2-stable versionShahzad
 
Exploration note - none windows based authentication for WCF
Exploration note - none windows based authentication for WCFExploration note - none windows based authentication for WCF
Exploration note - none windows based authentication for WCFShahzad
 
To study pcms pegasus erp cargo management system-release-7 from architectu...
To study pcms   pegasus erp cargo management system-release-7 from architectu...To study pcms   pegasus erp cargo management system-release-7 from architectu...
To study pcms pegasus erp cargo management system-release-7 from architectu...Shahzad
 
To study pcms pegasus erp cargo management system-release-6 from architectu...
To study pcms   pegasus erp cargo management system-release-6 from architectu...To study pcms   pegasus erp cargo management system-release-6 from architectu...
To study pcms pegasus erp cargo management system-release-6 from architectu...Shahzad
 
Pakistan management
Pakistan managementPakistan management
Pakistan managementShahzad
 
Corporate lessons
Corporate lessonsCorporate lessons
Corporate lessonsShahzad
 
What is future of web with reference to html5 will it devalue current present...
What is future of web with reference to html5 will it devalue current present...What is future of web with reference to html5 will it devalue current present...
What is future of web with reference to html5 will it devalue current present...Shahzad
 
Software architecture to analyze licensing needs for pcms- pegasus cargo ma...
Software architecture   to analyze licensing needs for pcms- pegasus cargo ma...Software architecture   to analyze licensing needs for pcms- pegasus cargo ma...
Software architecture to analyze licensing needs for pcms- pegasus cargo ma...Shahzad
 
A cross referenced whitepaper on cloud computing
A cross referenced whitepaper on cloud computingA cross referenced whitepaper on cloud computing
A cross referenced whitepaper on cloud computingShahzad
 
Software architecture case study - why and why not sql server replication
Software architecture   case study - why and why not sql server replicationSoftware architecture   case study - why and why not sql server replication
Software architecture case study - why and why not sql server replicationShahzad
 
Software Architecture New Features of Visual Studio 2010 / .Net 4.0 - Part 1...
Software Architecture New Features of Visual Studio 2010 / .Net 4.0  - Part 1...Software Architecture New Features of Visual Studio 2010 / .Net 4.0  - Part 1...
Software Architecture New Features of Visual Studio 2010 / .Net 4.0 - Part 1...Shahzad
 
From Windows Presentation Foundation To Silverlight
From Windows Presentation Foundation To SilverlightFrom Windows Presentation Foundation To Silverlight
From Windows Presentation Foundation To SilverlightShahzad
 
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
To Study  E T L ( Extract, Transform, Load) Tools Specially  S Q L  Server  I...To Study  E T L ( Extract, Transform, Load) Tools Specially  S Q L  Server  I...
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...Shahzad
 
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
To Study  E T L ( Extract, Transform, Load) Tools Specially  S Q L  Server  I...To Study  E T L ( Extract, Transform, Load) Tools Specially  S Q L  Server  I...
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...Shahzad
 
To Analyze Cargo Loading Optimization Algorithm
To Analyze Cargo Loading Optimization AlgorithmTo Analyze Cargo Loading Optimization Algorithm
To Analyze Cargo Loading Optimization AlgorithmShahzad
 
Whitepaper To Study Filestream Option In Sql Server
Whitepaper To Study Filestream Option In Sql ServerWhitepaper To Study Filestream Option In Sql Server
Whitepaper To Study Filestream Option In Sql ServerShahzad
 
Case Study For Replication For PCMS
Case Study For Replication For PCMSCase Study For Replication For PCMS
Case Study For Replication For PCMSShahzad
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 

More from Shahzad (20)

Srs sso-version-1.2-stable version-0
Srs sso-version-1.2-stable version-0Srs sso-version-1.2-stable version-0
Srs sso-version-1.2-stable version-0
 
Srs sso-version-1.2-stable version
Srs sso-version-1.2-stable versionSrs sso-version-1.2-stable version
Srs sso-version-1.2-stable version
 
Exploration note - none windows based authentication for WCF
Exploration note - none windows based authentication for WCFExploration note - none windows based authentication for WCF
Exploration note - none windows based authentication for WCF
 
To study pcms pegasus erp cargo management system-release-7 from architectu...
To study pcms   pegasus erp cargo management system-release-7 from architectu...To study pcms   pegasus erp cargo management system-release-7 from architectu...
To study pcms pegasus erp cargo management system-release-7 from architectu...
 
To study pcms pegasus erp cargo management system-release-6 from architectu...
To study pcms   pegasus erp cargo management system-release-6 from architectu...To study pcms   pegasus erp cargo management system-release-6 from architectu...
To study pcms pegasus erp cargo management system-release-6 from architectu...
 
Pakistan management
Pakistan managementPakistan management
Pakistan management
 
Corporate lessons
Corporate lessonsCorporate lessons
Corporate lessons
 
What is future of web with reference to html5 will it devalue current present...
What is future of web with reference to html5 will it devalue current present...What is future of web with reference to html5 will it devalue current present...
What is future of web with reference to html5 will it devalue current present...
 
Software architecture to analyze licensing needs for pcms- pegasus cargo ma...
Software architecture   to analyze licensing needs for pcms- pegasus cargo ma...Software architecture   to analyze licensing needs for pcms- pegasus cargo ma...
Software architecture to analyze licensing needs for pcms- pegasus cargo ma...
 
A cross referenced whitepaper on cloud computing
A cross referenced whitepaper on cloud computingA cross referenced whitepaper on cloud computing
A cross referenced whitepaper on cloud computing
 
Software architecture case study - why and why not sql server replication
Software architecture   case study - why and why not sql server replicationSoftware architecture   case study - why and why not sql server replication
Software architecture case study - why and why not sql server replication
 
Software Architecture New Features of Visual Studio 2010 / .Net 4.0 - Part 1...
Software Architecture New Features of Visual Studio 2010 / .Net 4.0  - Part 1...Software Architecture New Features of Visual Studio 2010 / .Net 4.0  - Part 1...
Software Architecture New Features of Visual Studio 2010 / .Net 4.0 - Part 1...
 
From Windows Presentation Foundation To Silverlight
From Windows Presentation Foundation To SilverlightFrom Windows Presentation Foundation To Silverlight
From Windows Presentation Foundation To Silverlight
 
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
To Study  E T L ( Extract, Transform, Load) Tools Specially  S Q L  Server  I...To Study  E T L ( Extract, Transform, Load) Tools Specially  S Q L  Server  I...
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
 
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
To Study  E T L ( Extract, Transform, Load) Tools Specially  S Q L  Server  I...To Study  E T L ( Extract, Transform, Load) Tools Specially  S Q L  Server  I...
To Study E T L ( Extract, Transform, Load) Tools Specially S Q L Server I...
 
To Analyze Cargo Loading Optimization Algorithm
To Analyze Cargo Loading Optimization AlgorithmTo Analyze Cargo Loading Optimization Algorithm
To Analyze Cargo Loading Optimization Algorithm
 
Asp
AspAsp
Asp
 
Whitepaper To Study Filestream Option In Sql Server
Whitepaper To Study Filestream Option In Sql ServerWhitepaper To Study Filestream Option In Sql Server
Whitepaper To Study Filestream Option In Sql Server
 
Case Study For Replication For PCMS
Case Study For Replication For PCMSCase Study For Replication For PCMS
Case Study For Replication For PCMS
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 

Recently uploaded

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
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
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
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...
 

To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hibernate Based Application

  • 1. NHibernate Performance Tuning To: Development Team By: Shahzad Sarwar Dated: 1st April 2010
  • 2. Table of Content 1Objective:...........................................................................................................................3 2Problem definition: ...........................................................................................................3 3Performance Tuning tips for NHibernate:.........................................................................3
  • 3. 1 Objective: To study the tips/tricks/Guidelines related to performance tuning for NHibernate based application. 2 Problem definition: Any fool can start a software to build, but to make it live on client’s production environment as a living legend is not easy task, it requires high end skills in Software Architecture. Performance is always a major concerns, which contribute to failures of software projects. OR Mapping is generally slower then direct ADO .Net connection. That is true for both nHibernate and LINQ2SQL. Applications which have a lot of data centric operations are not suited for NHibernate in general for OR Mapping. However application which have application centric operations or calculation going on are best suited for NHibernate or OR Mapping. So if you are making a Enterprise CRM Product, then NHibernate(OR mapping) is not a good choice because of inherited performance issues. ( Because of heavy data centric operations) If you are making a multi player online game or simulator, then NHibernate is a good choice because a few data operations are required and more processing is required at application logic. So think twice before starting a project and make good choice at the start of application and rest in peace rest of your life….:) Bad Architecture decisions cause trouble for whole development team and project. 3 Performance Tuning tips for NHibernate: After some googleing and reading online documentation, I have finalized, following list of 21 points regarding performance tuning for a NHibernate application. 3.1 NHibernate's SessionFactory is an expensive operation so a good strategy is to creates a Singleton which ensures that there is only ONE instance of SessionFactory in memory: public class NHibernateSessionManager { private readonly ISessionFactory _sessionFactory; public static readonly NHibernateSessionManager Instance = new NHibernateSessionManager(); private NHibernateSessionManager() { if (_sessionFactory == null) {
  • 4. System.Diagnostics.Debug.WriteLine("Factory was null - creating one"); _sessionFactory = (new Configuration().Configure().BuildSessionFactory()); } } public ISession GetSession() { return _sessionFactory.OpenSession(); } public void Initialize() { ISession disposeMe = Instance.GetSession(); } } Then in your Global.Asax Application_Startup, you can initialize it: protected void Application_Start() { NHibernateSessionManager.Instance.Initialize(); } 3.2 Fetching strategy is key to performance tuning in Nhibernate project. A fetching strategy is the strategy NHibernate will use for retrieving associated objects if the application needs to navigate the association. Two things are important: when is the association fetched, and how is it fetched (what SQL is used). Clearly understand and use following: Join fetching Select fetching Subselect fetching "Extra-lazy" collection fetching Batch fetching Also follow: Immediate fetching Lazy collection fetching Proxy fetching
  • 5. Best tip is to analyze the trade off b/w eager loading vs lazy loading. It varies case of case for implementation. 3.3 Make read-only classes immutable. 3.4 Multi query is executed by concatenating the queries and sending the query to the database as a single string. This means that the database should support returning several result sets in a single query. At the moment this functionality is only enabled for Microsoft SQL Server and SQLite. IMultiQuery multiQuery = s.CreateMultiQuery() .Add(s.CreateQuery("from Item i where i.Id > ?") .SetInt32(0, 50).SetFirstResult(10)) .Add(s.CreateQuery("select count(*) from Item i where i.Id > ?") .SetInt32(0, 50)); IList results = multiQuery.List(); IList items = (IList)results[0]; long count = (long)((IList)results[1])[0]; 3.5 Multi Criteria like Multi query allows to perform several criteria queries in a single round trip. IMultiCriteria multiCrit = s.CreateMultiCriteria() .Add(s.CreateCriteria(typeof(Item)) .Add(Expression.Gt("Id", 50)) .SetFirstResult(10)) .Add(s.CreateCriteria(typeof(Item)) .Add(Expression.Gt("Id", 50)) .SetProject(Projections.RowCount())); IList results = multiCrit.List(); IList items = (IList)results[0]; long count = (long)((IList)results[1])[0]; 3.6 NHibernate 1.2 supports batching SQL update commands (INSERT, UPDATE, DELETE) for SQL Server and .NET Framework 2.0 or above.Update batching is enabled by setting hibernate.adonet.batch_size to a non-zero value. 3.7 Most Important tip is to avoid looping b/w object collections , when conditional data fetching / manipulation is required. Looping b/w collection of large size can really hurt the performance. Use HQL to transform your conditions to Criterias that can really save you processing time. Lets take example of getting Voucher entities having voucher details collection with some conditions. So don’t traverse the collection of vouchers and voucher details, use HQL to fetch the required entities. System.Collections.IList list = null; NHibernate.ICriteria crit = Common.Common.Instance.GetSession.CreateCriteria(typeof(VoucherDetail), "VoucherDetail"); crit.CreateCriteria("VoucherHead" ,"VH"); crit.Add(NHibernate.Criterion.Expression.Eq("Account", objacc));
  • 6. crit.Add(NHibernate.Criterion.Expression.Eq("VH.SupInvNo", InvNo)); crit.Add(NHibernate.Criterion.Expression.Eq("SrNo", Convert.ToInt16(0))); crit.Add(NHibernate.Criterion.Expression.Not(NHibernate.Criterion.Expression.Eq("VH.Vouc herID", ID))); crit.SetFetchMode("VoucherDetail", NHibernate.FetchMode.Eager); crit.SetFetchMode("VoucherHead", NHibernate.FetchMode.Eager); setFinancialYearCriteria(crit, typeof(VoucherDetail)); list = crit.List(); 3.8 Use SQL Profiler and NH Profiler to view the queries generated by OR Mapping. 3.9 Use query plan to analyze the queries sent by nhibernate. 3.10 Create good indexes on tables to get better results. 3.11 Use “Database Engine Tuning Advisor” to get feedback from SQL Server regarding optimization. 3.12 Best practices for DB normalization can really help to solve the slow down of application. Bad DB design really kills NHibernate speed. 3.13 Using value type objects for your properties and components as opposed to reference types, when you have a choice, this will lower memory footprint. 3.14 Consider your logging strategy for production (less verbose) and usually disable show_sql in production. 3.15 When expensive data queries are envolved or there are limitations of OR Mapping coming up, it is better to use native SQL queries in NHibernate. That increases the performance of application. 3.16 In case of extreme database centric operations, store procedures can also speed up the performance. string sql = "exec GetJobExpenseAccounts "; NHibernate.ISQLQuery qry= Common.Common.Instance.GetSession.CreateSQLQuery(sql); 3.17 Avoid composite keys (exception legacy databases). Composite keys are problematic for database design as well as OR/M therefore avoid them. reference 3.18 Remove any columns and properties that you will never or should never need or use. 3.19 Have a good strategy for flushing and transaction management. Remember that if you commit a transaction that you do not need to flush the object. reference 3.20 Enable 2nd level cache and have a strategy for using it for some of your classes. For details view manual here. 3.21 Read Collection optimization tips in NHibernate documentation. For details view manual here. References: http://scottwhite.blogspot.com/2009/04/nhibernate-performance-tuning.html http://www.codeproject.com/KB/database/NHibernate_Perf.aspx http://www.codeproject.com/KB/database/NHibernate_Perf2.aspx http://www.iamnotmyself.com/2008/07/02/NHibernateTestingThePerformanceUrbanLegend.aspx http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx http://www.objectreference.net/post/NHibernate-and-Execution-Plans.aspx http://devlicio.us/blogs/billy_mccafferty/archive/2007/03/03/nhibernate-performance-tuning.aspx