Optimization Opinions

mskeel

Well-known member
Joined
Oct 30, 2003
Messages
913
Location
Virginia, USA
When writing code, what are your priorities? What about when you refactor? What kind of optimizations do you do and how far do you take it? What trade-offs are acceptable and where do you draw the line?

Post your opinions and specific examples of what you consider to be your "best practices" when writing a program. Any level of detail is acceptable. A low level concept might be pointer arithmetic or loop unrolling while a high level idea might be algorithmic (binary sort versus quick sort) or data-structure driven.

Ill kick it off. My priorities when writing code, generally speaking, are:

1. Testability/Reliability -- How easy is it to automatically test my application? Does it work correctly every time?
2. Maintainability -- How easy it to read/understand my code?
3. Performance -- How fast does it run?
4. Memory Usage -- this is hardly a concern these days, but can be occasionally
5. Disk Space -- At less than $1/gig these days this is almost silly to worry about.

Generally, If I can improve something lower on the list without sacrificing something higher, I will. So If I can improve performance without sacrificing maintainability, I will choose the faster implementation.
 
Quick background. My programs are created to run Test Equipment racks.
So here is what I think of when creating a program.

1. Ease of use for the operator. I have worked with engineers who always say they dont care, as long as they get a the results they want. Yeah that is nice, but if the operator has a hard time using it, then they get frustrated and also wastes time. I think what ever the operator can do, will do. If say pushing the "A" key will crash the program, I make sure if they push it, nothing will happen(That was just a simple example). I usually ask operators for inputs. I tell you what, this gets the respect from them. If I ever need something tested or need something from them, they dont hesitate to help. If one of the other engineers try and get something done, the operators tell them they will get it done when they have a chance.

2. Performance. In a manufacturing arena, time is money.

3. Memory and disk space. You talk about it is cheap to get, but not when you are on a budget. It is like pulling teeth most of the time to get more space and memory. Also with memory use, I try and use less, it gives me practice as maybe one day I can write for embedded chips on a circuit board.

4. Maintainability -- I try and keep my code easy to read. SOmetimes though with time restraints, they just want something to work within a few days. But I do go back and comment most things. When I do make say variables though, I name them in such a way you know what kind of variable and try and make the naem desciptive. (example: intAmpChannels - This tells the person it is an integer, and if working in my area, how many channels an amp has.) This also is tru when naming subs and functions.
 
Ive got to admit that the first four options you specified are probably what I would choose. I will add...

1. Self-documenting code - always useful to just be able to print out the code or click a button to generate the associated documentation. This saves oodles of time, allowing us to crack on with the more necessary tasks at hand.

2. I suppose, associated to this, would be readability. Some of the cr@p that Ive seen floating around my workplace... The people who write it should be taken out behind the garages and shot!

3. Performance and memory usage tend to go hand in hand, I believe. Compaction of data or processes tends to incur a performance hit, so this can be quite a battle ground. I do find .NET pretty good at handling this, though.

4. Data quality and error checking - of the utmost importance. I cant remember who it was that said:
Software design is a race between the programmer and the universe - the programmer to produce bigger and better, more idiot proof software; and the universe to produce bigger and better idiots!

Also, most of my programs tend to use different types of optimisation in different areas, therefore all of the above can be appropriate.

(I will maintain, though, that the most important to me is readability and structure)


Paul.
 
Last edited by a moderator:
2. I suppose, associated to this, would be readability. Some of the cr@p that Ive seen floating around my workplace... The people who right it should be taken out behind the garages and shot!

Yes they should. At my old job, they had an embedded so called "Software Engineer". I am not at all any good at C language, but I can read it and get an understanding of it. The design engineer showed me the program so i could get a good laugh. You could not tell what the heck was going on. Here is an example of what I mean.
His variables labeled.
I will put it in VB terms but you will get the point.

Dim D1 as string
Dim D2 as string
Dim D3 as integer and so on

They finally "LAID" him off after over a year. I couldnt believe they kept him that long.:rolleyes: :eek:
 
Its interesting to see the differences emphasized between a business application developer (I code mostly analysis tools these days) and an embedded/hardware application developer.

techmandbd, you raise an extremely valid point: usability optimizations. Thats a whole subject unto itself and a very important one too. If you could see the awful UI designs Ive seen in some of the custom tools Ive had to use Im sure you would scream. The buttons are thrown on the form anyway they can be with no logical order, everything is a complicated multi-step process -- its awful.

The hard part is that my clients dont generally value high quality UIs. To them if you create a perfect, pretty, well engineered GUI that looks great and works perfectly they look at it as a waste of time and money. Its amazing really. I think youre right on the spot -- similarly to manufacturing, in testing and analysis time is also money and bad user interfaces cause unnecessary fatigue and make us think too much about how to use the darn tool instead of the problem were trying to solve!

mandelbrot -- what sorts of data quality management and error checking do you do? Do you use contracts, assertions, try..catch, ...?
 
mskeel said:
what sorts of data quality management and error checking do you do? Do you use contracts, assertions, try..catch, ...?

I do implement each of those to varying degrees. I must admit that, until a none beta release, I dont heavily use Try..Catch blocks. I tend to want the code to fall over so I can suitably debug. We go through the usual debug phases, but also through client debug sessions. This usual means putting the software into the field and seeing how it copes. As we work in the NHS this isnt such a problem. (Of course if we were talking about more serious software for heart monitors etc, then we wouldnt do this, but the chance of us writing anything like that is pretty damn slim :p !!).

I used to believe, in my uneducated days, that interfaces were a waste of space ... how wrong I was - I see their usefulness now, and frequently employ them to fill the gap.

Its not just coding techniques, though. The majority of data quality is handled by how you design and implement the associated database. Normalisation is a huge part of the process. If theres even the slightest possibility of getting away with it, Ill use a pick list or similar. The technology exists to quickly and easily implement coded lists in .NET, and it so restricts problematic information. Even the DatePicker control lessens the chances that a user will get the wrong date. Typing in your date is a bit of a no brainer and suceptable to potentially huge errors. If you take this away from the user by supplying a graphical control youre instantly reducing the chance of gaff data. Once again, by referring to the past ways that this has been achieved......

Another useful control, though I tend not to use it, is the ErrorProvider - easily restricts values on webpages. In actuality, however the other coders in the team use Javascript and Ajax to error trap the data on the webforms.
 
Personally I put maintainability at the top of my list, this includes coding style, commenting style and having appropriate unit tests.

In terms of optimising for performance I would never deliberately do something a slow way if the fast way meets the above criteria however I would always prefer a more maintainable version over a faster version unless the performance is a real issue. (by real I mean falling outside of acceptable behaviour).

I do use Try ... Catch early on in development but follow the guidelines of only trapping errors I can deal with where I can deal with them and never catching just Exception (or Object :confused: either), that way I can test that the correct errors are being raised and unexpected errors get noticed.
 
I dont know if anyone else does this talking about maintainability, but I have a habit of putting things in alphebitical order.

And I use the region feature. I have a region for subs functions, controls, etc.. and those too are put into order. Here is a quick sample of when I dim variables
Code:
    ********Variable from DLL or Classes *******
    Dim ACC As New PrinterPortClass
    Dim GPIBCom As New HBGPIBControl
    Dim IconsDLL As New HBIconusage
    Dim PT As New PassThruVar

    ******Double Variable****************

    ******Form Controls****************
    Dim frmAmpChann As New frmAmpChannelsMonitor
    Dim lblAmpMon(30) As Label
    Dim picAmpMon(30) As PictureBox
    ******Integer Variables**************
    ******String Variables***************
    Dim strFileNameIgn As String Name of the Ignition file for the McS1 to recognize to turn on.
    ******Thread Variables*************
    Dim thrdPowSup As Thread  Thread to monitor power supply
    Dim thrdTempChamb As Thread  Thread to monitor Temperature Chamber

AND if they are not, it bugs the heck out of me. If I dont put it into order, maybe when I am doing something quickly, it will bug me until I put it in correctly.
 
PlausiblyDamp said:
In terms of optimising for performance I would never deliberately do something a slow way if the fast way meets the above criteria however I would always prefer a more maintainable version over a faster version unless the performance is a real issue.
At what point do you say that performance has become a "real issue"?

techmanbd said:
AND if they are not, it bugs the heck out of me. If I dont put it into order, maybe when I am doing something quickly, it will bug me until I put it in correctly.
LOL fReak!! :D Seriously though, the best part is that this technique doesnt cost anything at compile or run time so if it means less bugs...go for it. I tend to group my variables by functionality or use though the order within groups is almost always arbitrary.
 
I personally dont find much need for prioritizing when it comes to optimizing my code. Ive adapted a programming style where as I code I evaluate the potential for unacceptable use of resources (disk space, RAM, CPU). I am also a minimalist, preferring to keep things as simple (which is not the same as "easy") as possible. I often use structs instead of classes when there is no impact on maintainability or readability (saves on RAM and garbage collection). I often use simple binary formats for data because they are more compact and, in some ways, less error-prone than human readable formats. Dont get the wrong idea. I understand the need to find a balance between the time it takes to complete the project, maintainability, and the level of optimization. I am not micro-optimizing. I am simply diligent and conscientious when it comes to coding.

So, when does performance become a real issue? Simple. When it impacts the users experience. Speed optimizations are of relatively little importance until you encounter a bottleneck and you find yourself looking at a noticeable lag or unusually slow progress bar.

For example, I made a post here quite some time ago explaining that constructors are an order of magnitude slower than a normal instance method when it comes to initializing a struct. Well, even though I deal with structs much more often than your typical C# programmer, I still use constructors 99% of the time. If I need to initialize an array of structs and the GUI freezes for a second when this happens, then I use a non-constructor initialization method.
 
techmanbd said:
I dont know if anyone else does this talking about maintainability, but I have a habit of putting things in alphebitical order.

And I use the region feature. I have a region for subs functions, controls, etc.. and those too are put into order. Here is a quick sample of when I dim variables
Ha! Ha! Ive seen it all now!! Thats even worse than me! I must admit that I hate seeing a ragged line on the right of the code, so I will, if the situation is right, organise the lines into line length order (either up or down, it doesnt matter which)...
Code:
Private properties...
Private _isDirty As Boolean = False
Private _Title As String = String.Empty
Private WithEvents _AllDates As RegisteredOccurrences
Private variables...
Private contextNode As TreeNode = Nothing
Private nodeReports As TreeNode = Nothing
Private nodeWindows As TreeNode = Nothing
Private nodeDates As TreeNode = Nothing
Private nodeBase As TreeNode = Nothing
Private nodeSync As TreeNode = Nothing
Private nodeHelp As TreeNode = Nothing
It can become a bit of a pain at times, but it does make the code a little more readable...... Honest!
;)
 
Quirky coding styles

I must admit that I hate seeing a ragged line on the right of the code, so I will, if the situation is right, organise the lines into line length order (either up or down, it doesnt matter which)...

Funnily enough, the strict formatting is one of the things I find most annoying when Im forced to use VB, as I like to align things using tabs and spaces in the middle of statements. My C++/C# usually looks like this:

Code:
private Image               m_backbuff;
private double[]            m_data;
private AudioBoxDisplayMode m_mode;
private VoiceSample         m_sample;

My code tends to read like its been written by someone with OCD. Every object I declare has its members placed in this very strict order:

  1. Static fields
  2. Instance fields
  3. Static properties (public, protected, internal)
  4. Instance properties (public, protected, internal)
  5. Static constructor if needed
  6. Constructors (public, protected, internal)
  7. Destructor/finalizer if needed
  8. Static methods (public, protected, internal, private)
  9. Instance methods (public, protected, internal, private)

Within each group, members are in alphabetical order. In addition, all overloads, including constructor overloads, are declared in the order of number of parameters they take, so a parameterless constructor always comes first.

Ive developed this style over a long period of time as I find it is the most logical way to organize code.

Back to the original post, I would have to agree with mskeel, that accuracy comes first, followed by maintability, followed by efficiency. Depending on the application, scaleability may also be a concern but it usually manifests itself as a combination of all three.

;)
 
Re: Quirky coding styles

I do order things in a similar manner, also. All of my declarations, events, delegates, properties, methods and localised classes/structures go into their own regions. I also try to keep similar functions together in the code.

One of the chaps I work with attempts to order his code blocks in execution order... I find that more difficult to visualise, but each to their own!
 
Re: Quirky coding styles

I know I am a freak,:p But really I am not like that in every day life. If I am working out in the garage on my bike or car, I dont have the need to put my tools away right away. I leave them out on the bench, maybe for a few days until I get a chance to put them away.

I think when I am creating a program, since they are for the company, I think that when I am not here anymore, it makes it easier for someone to find everything. I hope anyways.

I think this stems from coming into a company, trying to fix someone elses code who had left, and wasnt a readable code, and would have to spend a lot of time trying to decipher the code because it wasnt labeled nicely and had subs, functions, etc.. just thrown where ever they felt like it. I know I can use the search, but sometimes faster to go where you know it is.
 
Re: Quirky coding styles

techmanbd said:
If I am working out in the garage on my bike or car, I dont have the need to put my tools away right away. I leave them out on the bench, maybe for a few days until I get a chance to put them away.
Yeah, but I bet youre one of those wierdos who has the big board with the hooks in, and youve drawn around every tool so that its got a distinct place! ... Come on - admit it!! ;)
 
Re: Quirky coding styles

Yeah, but I bet youre one of those wierdos who has the big board with the hooks in, and youve drawn around every tool so that its got a distinct place! ... Come on - admit it!! ;)

Um, well, I didnt draw around the tools.;) But yes, I have the peg boards. Started this after being trained as a Yellow Belt in Six Sigma about 4 years ago.
 
Back
Top