You are here: DIME Home > Software Reviews > Performance. Practical recommendations


Performance. Practical recommendations

Even the best performing component can be hindered by incorrect use. Below we provide practical recommendations on what should be used or avoided in application programming. Following the tips below you will be able to create applications with the same efficiency as this demo application. We also provide source codes for this example to show how easy it is.

Author: mopeljenny
Date: Jun 15, 2012 - 6:24:20 AM


Printer FriendlyPrinter friendly page

Even the best performing component can be hindered by incorrect use. Below we provide practical recommendations on what should be used or avoided in application programming. Following the tips below you will be able to create applications with the same efficiency as this demo application. We also provide source codes for this example to show how easy it is.

It is supposed that programmers already know general principles of application design. Nevertheless, we shall provide some useful links for better understanding of .Net environment and tools for writing managed code: Writing Faster Managed Code: Know What Things Cost

It is necessary to pay attention to grid characteristics in different working modes, to evaluate data volume to be displayed and to find a relevant chart for better understanding of grid use.

Use ThreadSafeBindingList instead of BindingList for the following reasons:

1. BindingList has poor implementation when working with objects that implement INotifyPropertyChanged interface. Here you can find more information on BindingList performance issues. Use ThreadSafeBindingList instead, as it doesn't allow BindingList to subscribe to events of objects that it contains.

2. Another reason to use ThreadSafeBindingList instead of BindingList is related to implementation of MulticastDelegate used in events. With one subscriber, this delegate consumes minimum memory resources, but when there are two or more subscribers, it creates an internal subscriber collection that increases memory consumption dramatically. The grid always subscribes to objects that implement INotifyPropertyChanged interface and BindingList is the second subscriber.

If BindingList is used together with objects implementing INotifyPropertyChanged interface, it is better to avoid firing notifications with non-existent data object properties. It is mainly required because when a binding list receives such notification it checks whether the firing object has the specified property. If the firing object doesn't have such property, the BindingList generates ListChanged event specifying Reset reason and forcing the grid to rebuild all its contents.

Avoid using INotifyPropertyChanged interface, unless it is required. If the object doesn't change at run-time, it is better not to use this interface to save memory and CPU resources.

Add data to the end of collection (List, BindingList, ThreadSafeBindingList etc). Otherwise, internal implementation of indexed collections will move and re-index all data starting from the newly added index.

Avoid adding data to a binding list with more than 10 000 items when the grid is sorted. Stop sorting to improve performance. However, if you need to add large amounts of data in real-time to the beginning of the grid, it's better to use the following:

grid.Sort.Enabled = false; grid.DataSource = _datasource_;

//Add a single object to the beginning of the grid grid.Nodes.Insert(0, _new_object_);

//Add a single object to the beginning of the binding list IBindingList bl = ...; bl.Insert(0, _new_object_);

Although the grid is thread-safe with INotifyPropertyChanged and IBindingList interfaces, use the GUI thread to work with it. This is mainly important for adding large data volumes. Some optimization algorithms work better when there is no need to switch between threads. Please also note that BindingList is not thread-safe.

Have only one message loop per application. Don't create grids in different threads.

Let us assume that the computer resources are not limitless. Theoretically the maximum performance can be obtained if the number of threads equals to the number of processor cores. While a lot of threads are creating, they aren't working in parallel. In this case cores allocate time slices to threads based on their priority and consistently perform context switches (context switch is relatively expansive operation). Note, maximum time slice is about 10-15 msec.

We have also take into account that each control paints its content in the GDI/GDI+ device (via the Graphics object). While painting from one thread all others wait for GDI device to perform painting in its turn. Therefore if we start many message loops -- it doesn't mean that we accelerate the application. In other words the application losses time on context switches and on drawing in GDI device.

From our point of view the application should have only one message pump. Windows has additional mechanisms to optimize content drawing and we are not sure that they work in case of multithreaded environment. Of course, business logic can work in any thread, but the graphical thread should be only one in the application.

Use MethodInvoker to synchronize threads.

In multi-threaded applications every call should be synchronized with the main thread containing windows message loop. Both Control.Invoke and Control.BeginInvoke methods may accept different delegate types and their parameters. However, this causes a serious performance issue as they call Delegate.DynamicInvoke(params object[] args), which in turn uses low-performance reflection. At the same time, for some delegates such as EventHandler, MethodInvoker and WaitCallback the code is called directly. In the time of code execution the delegate is checked for belonging to one of the above types with specified number of parameters, and if it doesn't -- DynamicInvoke() is called.

From practical point of view the synchronization process should look as follows:

someControl.BeginInvoke(new MethodInvoker(delegate { //a code here }));

Use objects of arbitrary classes instead of collections of values of string[] type, etc. It is more convenient and objects of arbitrary classes consume less memory than string collections.

Don't format values directly in data objects, i.e. if an object property is to return date, this field should return DateTime object type instead of string type. Use data formatting if needed. If properties return strings, they can be compared incorrectly during data sorting. Besides, comparing two strings requires more CPU resources than comparing two DateTime objects.

class DateExample { ...

//Bad idea public string FormattedDate { get { return string.Format("{0:yyyy-MM-dd}", _date); } }

//Good idea: the property should return non-formatted value [Format("yyyy-MM-dd")] public DateTime Date { get { return _date; } } }

Use the event-driven model, if possible. On global scale it is more efficient than searching for rows in one or more grids with dynamically changing data.

Share the same business objects in different grids. Use declarative binding. This simplifies the application code and significantly reduces memory consumption.

Avoid using unnecessary wrappers. Use declarative binding instead of creating intermediate classes.

Use statically declared EventArgs for data fields to avoid creating numerous short-lived objects when sending notifications via INotifyPropertyChanged interface.

class MyDataObject : INotifyPropertyChanged { private static readonly PropertyChangedEventArgs Value1Args = new PropertyChangedEventArgs("Value1");

private string _value1;

public string Value1 { get { return _value1; } set { if (_value1 != value) { _value1 = value;

//Bad idea: short-lived object is created FirePropertyChanged("Value1");

//Good idea: notify with an immutable static object FirePropertyChanged(Value1Args); } } }

private void FirePropertyChanged(string fieldName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(fieldName)); } }

private void FirePropertyChanged(PropertyChangedEventArgs args) { if (PropertyChanged != null) { PropertyChanged(this, args); } }

public event PropertyChangedEventHandler PropertyChanged; }

Work with business logic objects directly instead of calling Cell.Value/Row.DataAccessor["fieldId"].Value

TypeDescriptor/PropertyDescriptor are used to display values in cells when working with arbitrary data types. The following code demonstrates value extraction from data objects.

MyDataObject dataObject = ...; dataObject.Value1 = "some value";

PropertyDescriptor property = TypeDescriptor.GetProperties(dataObject)["Value1"]; object value = property.GetValue(dataObject);

This working principle is the same for all grids of all vendors. The main issue is that PropertyDescriptor.GetValue() method uses reflection. NetGrid has an optimization that enables it to receive notifications from INotifyPropertyChanged/IBindingList without calling data object getters. Values are required only at the time of painting and only for visible cells. If the grid has a lot of rows, most of them are invisible and this approach significantly saves CPU resources. It is worth considering in application development. As an example, let's review subscription to Grid.RowUpdated event:

grid.RowUpdated += delegate(object sender, GridRowUpdateEventArgs e) { //This callback is called each time when a notification from INotifyPropertyChanged received.

//Using of custom object will reduce CPU consumption MyDataObject myObject = (MyDataObject) e.Row.DataObject; decimal lastPrice = myObject.LastPrice;

//The following call will use the reflection. Try to avoid. lastPrice = (decimal) e.DataField.Value; };

Use new Row.IsInVisibleBounds property added to version 2.8.0.

When updating data in real time in applications, the grid stores highlighting information for each updated cell. This default behavior causes serious consumption of memory resources in addition to CPU resource consumption due to processing large volume of information. As most updates can occur outside the visible area, the programmer can save CPU resources by using the new property.

//Disable authomatic highlighting (from INotifyPropertyChnaged interface) grid.Highlighting.Enabled = false;

//This callback is called each time when a notification from INotifyProeprtyChanged received. grid.RowUpdated += delegate(object sender, GridRowUpdateEventArgs e) { //Handle updates only for visible rows if(e.Row.IsInVisibleBounds) { //Using of custom object will reduce CPU consumption MyDataObject myObject = (MyDataObject)e.Row.DataObject; double delta = myObject.LastPrice - myObject.PrevPrice; if(delta != 0) { Color color = delta > 0 ? Color.Green : Color.Red; //highlight the 'LastPrice' cell with specified semi-transparent color for 2 seconds e.Row["LastPrice"].Highlight(TimeSpan.FromSeconds(2), Color.FromArgb(50, color)); } } };

We hope that these simple recommendations will help you create efficient and high-performing applications.

Dapfor .net grid has been created by professional developers with extensive experience in banking and telecommunication fields. Dapfor provide best .net performance grid which is adapted for real-time applications (trading application, real time trading, real time blotter) and displaying huge data volumes. Thread safety makes it safe to use with MVVM model.



View all articles by mopeljenny

Link to this article:

Code to copy: <a href="http://www.dime-co.com/software-reviews/Performance-Practical-recommendations.shtml">Performance. Practical recommendations</a>




Related Articles...

Spark Your Music Life with Best Mac Audio Converter

Jul 5, 2011 - 10:55:32 PM

As a  music lover, I have almost thousands of music, and I listen to music wherever I  go and whenever I have time. With the update of digital devices, we still meet  lots of music formats problem. My iPod may not support the formats of the music  I like very much. I almost become mad at that time.... [Read the full story]

Test King - A Miracle Tool For Professionals In IT

Jun 21, 2011 - 11:46:20 PM

Test king is the Microsoft MCITP Preparation. It helps the students and individuals who want to do legitimate Microsoft MCITP Preparation by creating modular packages which is combined into full Microsoft MCITP Preparation Certified training. This type of training is affordable and flexible for every professional. This method allows the schedule of the professional to be free and train when it is convenient for the candidate.... [Read the full story]

How to Convert FLV videos to iPad on Mac OS X

Jun 13, 2011 - 10:02:44 PM

Want to convert your FLV videos to iPad friendly formats and then enjoy them on your new iPad's big, beautiful, Multi-Touch LED screen? It's a hassle to get all the way to the end only to discover that your video file won't play on your iPad. I highly recommend iSkysoft iPad Video Converter for Mac, which provides optimized preset for your iPad so you don't need to worry about the settings for your iPad or iPad 3G (iPad 2 included). In addition, it will preserve the video quality to help you to convert FLV to iPad Mac perfectly.... [Read the full story]

Network Performance Management Key: Steps to Secure the Best Network Performance Management Software for A Helpdesk

Jun 1, 2011 - 12:11:00 PM

Each one of the IT professionals you are in charge of is capable of working with nearly all company related situations that may arise. However, there are days when it seems like you have a steady stream of help desk tickets flowing through your Inbox. It seems like every employee in the company has a concern that needs fixing immediately. You feel like panicking, but instead you simply open up your helpdesk software and let your network management key do its magic.... [Read the full story]


Newest Articles in Popular Topics:

Business & Marketing Computers & the Internet Entertainment Health & Fitness
Finding Ways To Save Money And Maximize Revenue In Business
Cooper's Golf Park Tees Off Their New Website
Fiinovation Adjudged CSR Team of the Year & Caring Company at World CSR Day
Reasons Why Kale Realty is the Best Real Estate Firm in All of Chicago
Montreal Tech Startup Kangaroo Rewards Launches Mobile Loyalty Program for Local Merchants
It is time we break out of the SEO Shelter
3 Strong Reasons You Should Start Your Own Blog
Evolve Your Career With CompTIA A+ Certification Exam
High speed VMware Backups - Powered by UltraBlaze(™) from Vembu
Things to Consider When Selecting a Domain Name for Your Website
Fling Boom "Launches" This Holiday Season
Beautiful Abstract Canvas Art is Up for Grabs
Buying Art as a Gift: Tips From an Expert
Complete Guide to the 2014 Gatlinburg Fine Arts Festival Released by Jackson Mountain Homes
Learn Blues Music Online-Alternative to Traditional Piano Lessons
Causes and Treatment of Acne
What Type Of Constipation Home Remedies Are There?
Manual Wheelchairs: Buying One
Instant Facelift with Dental Implants
Lasik Surgery Leading Correction Of Vision Issues

Home & Family

Shopping

Sports

Travel
Enhance Your Learning Experience Through Best Responsive Elearning Development Tools
Best Apps for Learning German
Esvees is Cranbourne's Elite Hair Dressing Company
Ozone Generator
Practical Tips When Choosing Gates and Gate Openers for Your Home or Business
Why Cases are Required for Mobile Phones?
Are Dealership Services Worth It?
2015 Jeep Grand Cherokee Named Must-Shop SUV for Towing from AutoTrader.com
Online Selling With An Appraisal Advantage
Macsome AudioBook Converter released New Version V2.0.4
Aditi Ashok signs off with a double
Softball Coaching: Avoid Becoming A Nattering Nabob of Negativity
Softball Coaching Tips - The Funnel Approach
Pick Up Specialized Advice on Jumping Exercises Which Are Highly Effective
Vertical Jump Training Tactics to Increase Your Athletic Performance
Tips for Choosing the Right Paris Short Lets
Hostels - the best choice for working womens and college students
Perfect holiday? Book a cruise and sail in Croatia!
Say Aloha to Your Best Vacation Ever with Kohala Coast Properties
The Perfect Guide for a Fantastic Family Trip to Kansas City

 



Follow & Share Your Favorite Video Articles

Tell a Friend About This Site



Chamber of Commerce - on the Web logo



Subscribe to the eMarket SmartsTM Newsletter in order to keep up to date with what's happening with dime-co.com, get the emails on new video articles, featured articles, and more. Your privacy is always protected. We never rent, sell or trade your private information

:
:

Service provided by GetResponse Autoresponders


Recommended Associates


Latest Articles in All Categories


Putting Up a Small Commercial Printing Business
So You Might Be Unemployed And Desire To Become A San Francisco Real Estate Investor Now
Meditation and Mindfulness: Dealing With Emotion
CPA Websites: Five Essential Ideas for Composing Convincing Articles
Set Goals In Order to Come Up With Your Action Plan
Is the Air in Your Home Safe to Breathe?
Coarse Fishing Tackle Review: The JW Young 13ft Trotter Rod
Section 1031 Exchanges For San Diego Real Estate Investors
Phoenix Real Estate Investing For Highest Possible Earnings
Legendary are the Volk Racing TE37 Wheels
Developing the Next Generation Wall Station (ChaseDesk™) for Healthcare - A Case Study
What are step down transformers?
Introducing Sharehype, the Revolutionary Tool for Online Marketers
Rewards To Shopping For Austin Real Estate On The Web
Hydroponics for Beginners



Do you write?

Would you like submit your articles and have them approved on a priority status? Find out more about how you can become a Priority author for pennies a day! Click here.

Dime-co.com Home
  • Business (9328)
  • Computers & The Internet (5740)
  • Entertainment (1348)
  • Family (958)
  • Finance (1963)
  • Health (4246)
  • Home and Living (6670)
  • Marketing (6113)
  • Shopping & Product Reviews (2624)
  • Sports (694)
  • Travel and Vacations (1689)
  • Video Articles (1)
  • Editors Pick (1)