Optimisation in C/VB

I am an application programmer - who has just got into application's programming - I have never thought about optimising programs before - I just like to have them well designed and working to spec - I write application programs solely and have been attempting to find some good books on code optimisation and firstly work out if i need to optimise at all, I feel that why the algo. is still in my mind and on paper it is hard to optimise only after it is running and being measured - is this true for most coders ??
Who is Participating?
mr_krishnaConnect With a Mentor Commented:
Some of the simple optimization rules as follows for VB.

1. Don't use Variant datatype whenever you need necessarily. This will give lot of difference for performance.
2. In declare statements, for one dim declare one variable only. For example dim temp as integer,temp1 as integer. This you will declare in two dim statements.
3.Don't use Goto's.
4.If possible as less you use Public variables is good.
5.When you open a recordset then after completing the operation then immediately close that recordset. At the same time open one connection for your project. If you want to open more than one connection necessarily close connections.
6.Use with as much as possible.
7.Becareful using collections. Set collection = nothing is more important.
8.Whenever you make an exe, before making an exe restart your machine and then start making exe. This will minimize some errors in exe's.
9.Passing big variables ByRef rather than ByVal.
10.Use variable instead of constants.
11. In sometimes using API's is more faster than functions.
12. If forms are not used in your memory use Unload instead of Hide.
I ALWAYS, write it once using the first method that pops in my head...

And then I re-write the parts/pieces that are too slow.

However, I generally have very detailed specs and design before I write one line of code.  Like a conceptual model...
It is known that writing a program in C or C++ usually produces much faster code,
so one way to optimize performances is to transfer some code from VB to C DLLs,
or to write an OCX with Visual C++.

Without getting that far, there are some tricks you can use in VB, the simplest is to compile the application to native code.
Usually a better knowledge of your developing environment will help you to plan in advance which type of approach to use when beginning to write the code.

I rarely use the last method, which is to insert profiling code into the application to find out what parts are running slowly, since I find this way unproductive, but it may depend from the type of applications I usually develop.

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Some optimizations take place over the years, as you reuse common routines and techniques and see opportunities to improve them in the process.  Many languages have soft spots that can be leveraged to improve performance.  For instance, in VB you can try to minimize useage of temporary string generation, something that happens each time you do
and so on.  Also, restricting most of your code to integers and avoiding floating point will aid in improved performance.  And generally, looking at your code to see that you do just the minimum necessary to get the job done will improve your programs. Boil the code down to the essence of what needs to be done, and it increases understanding, maintainability, and program speed.  Somehow, whenever I've optimized a program, it always winds up with much less code than it started out with.
Optimization is hard with modern languages. Sometimes you'll run into conflicts with the compiler optimizations. Additionally the resulting object is well hidden so you can't really tell what is going on. As a general rule tho there are things that help in almost all cases.

First, use declared constants wherever possible.
Don't use a variable when a constant will do. The compiler will generate faster, inline code instead of variable references.
Declare all your variables and use the simplest type possible. Never use a real when an integer will do.
Reduce the use of VARIANT data types as much as possible.
Tighten your loops.
If you have a situation where you need a property of an object several times copy it into a var first and reference the var instead of the object.
Examine your code and concentrate on the sections that get executed a lot. Don't spend time optimizing code that only executes once, you'll get much greater returns on the inner loop stuff than the init code.
Keep your algorithms tight. I've seen the old "Prime Number" generator written where the loop tests from 3 to N/2 when actually you can test from 3 to SQR(N) and do it with a step of 2. This tremendously reduces the execution time of the loop. An ounce of algorithm optimization is worth a pound of hardware.
Reduce your I/O. Don't do single byte file I/O. Grab a block into a var and process THAT instead. Set your lock size to match the blocking factor on the media.
Execution speed is subjective. If you have a longish process with NO operator feedback it will SEEM longer than if you implement a progress bar or some other feedback ticker.
Overlap execution. Throw your splash screen up FAST and that will cover some of your initialization time.
If performance is really an issue invest in a code profiler. This will pinpoint the areas of your code that take the most execution. Typically 5-10% of the code represents 90-95% of the execution overhead. If you can identify that 5% and really optimize it you'll get your best return on your optimization efforts.
Talk with the customer and find out where they perceive the bottle necks to be. Often where you think the trouble is isn't where the customer sees the problem.
1. The best optimization is to use better algorithms that is if you figure out a better way to do something, then use that.  For example you can "micro" optimize a Bubblesort to death, but for most cases it will never catch up with a Quicksort.

[I call fixing a piece of code in line a "micro optimization" and fixing/changing the algorithm a "macro optimization"]

2. The 2nd best optimization is to concentrate only on the slowest parts of your program.  For example consider a program that executes three procedures
A takes 1 second
B takes 9 seconds
C takes 90 seconds

Let's say you decide you decide to evenly spread your effort (thinking: I'll optimize everything).  First off micro optimizing 'A' is nearly pointless.  Even if you improve it so much that it is nearly instanteous you've at most made a 1% speed improvement in the overall program.  Optimizing 'B' is not much better, doubling the speed of this proc, produces only a 4.5% increase in overall speed.  

You would be much better off concentrating all your efforts on function C, as even a modest improvement (10%) produces a better result than any likely outcome of your efforts on A and B.

To find out what is the slowest procedure you can use profiling, or insert timers.  You may be surprised at what the slowest procedures in your program are.  

For most programs I/O and database procedures are the slowest.  [if a SQL query this is a really long topic in itself]

Combine this with tip #1 for the best results (that is to say improve the algorithms of the slowest parts of your program).

3. The next best optimization is to increase the "perceived speed" or your program.  Users generally don't like sitting in front of a screen where nothing is happening.  Many studies of have shown that even when the actual speed is slower, you can fool them into thinking it's faster.  An example from my own personal experience is when displaying an image we had two ways to do it: (i) Retrieve the whole image and paint it on screen in one go, (ii) Paint the image as each part was retrieved.  All users perceived (ii) as faster, but with a stop watch (i) was actually faster.

4. Modern compilers mess around with your code.  They often perform "micro" optimizations on sections of code much better than you can.  "Tricky" code can sometimes confuse the compiler so it can't optimize.

5. Regarding optimizing algorithms, there's a chapter in
Code Complete : A Practical Handbook of Software Construction
Steve McConnell / Paperback / Published 1993
Microsoft Press; ISBN: 1556154844
$28 from www.amazon.com
URL is

Most of the _techniques_ are applicable to VB (in my opinion this book is well worth getting anyway)

6. Some of the biggest improvements with "micro" optimization are to mess around with your code in loops.  Messing around with a line of code that executes only once, usually has little effect.

i. Move stuff outside loops if it doesn't need to be inside loops

FOR X = 1 TO 1000000
   ' Do some stuff
   ' Do some other stuff

If 'Do some stuff' is the same every time, change the loop to
' Do some stuff
FOR X = 1 TO 1000000
   ' Do some other stuff

Sometimes you can get a similar effect, with a bit of jiggling the code even when "Do some stuff" is not exactly the same each time.

ii. Make inner loops the largest range

FOR X = 1 TO 1000000
  FOR Y = 1 TO 1000
     ' Do something with X,Y

In the above example, the overhead of managing the Y loop happens a million times, changing this to

FOR Y = 1 TO 1000
  FOR X = 1 TO 1000000
     ' Do something with X,Y

Means the overhead of managing a loop (in this case the X loop) happens only 1000 times.

iii. In general for loops, look very carefully at code inside the loop, this is usually a big bottle neck as any slow algorithms hurt you more than once.

7. I can't emphasize this enough, TIME EVERYTHING
i. Code you think is faster, often isn't (or doesn't make a noticeable difference).  IIRC McConnell's book has an example of this
ii. You want to concentrate on the slowest parts of your program as said in tip #2
visit http://www.geocities.com/SiliconValley/Lab/1632/ and look around for optimizing
I'll add some VB-specific stuff to Answers2000's excellent comments:

*  if doing COM (or OLE automation) programming, take advantage of the With keyword.  For example:

'Use this
With myObject
  .name = "Fred"
  .address = "Somewhere"
End With

'Not this
myObject.name = "Fred"
myObject.address = "Somewhere"

*  Again, in COM or OLE Automation, use early binding if at all possible.  That is, don't use CreateObject and the "Object" type.  to work with an object if you can create a typed reference to it.  This makes an incredible difference.

*  If you're using VB4, then you have an excellent tool at hand.  It's called the code profiler.  It doesn't install with VB4, but is on the CD-ROM.  I believe it's in a tools directory.  You basically copy to a dir on your hard drive.  Read the help files and _use it_!  It instruments your source code to produce timing stats, and writes them into an Access database (you don't have to have Access).  I did a lot of performance tuning on a custom OLE client/server app using this tool.  For some reason, they seemed to have dropped it from VB5 (don't know about 6.0 yet).

Good luck...

Mike Thomas
Digital Answers, LLC
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.