Home > Writings > Programming > Using Assembler in Delphi > Basic Principles

Using Assembler in Delphi

Basic Principles

During the implementation phase, there are several general principles you should follow. The first important rule is: keep your routines as short as possible. Assembler should be used for some real core activity in which performance and simplicity are essential. So, in most cases, you can manage with fairly short and specialised routines. If you see that you have plenty of long pieces of assembler in your project, you are probably over-enthusiastic about it.

Secondly, keep the routines readable by commenting them in a meaningful way. Because of the basic linear nature of assembly code, the individual statements are quite easy to read. Comments are needed to clarify how you want to implement the algorithm, so that a third party will immediately understand what is going on. Your comments need to add valuable information for the readers of your code. So, the following is clearly wrong:

inc edx {increase edx}

Such comments are totally pointless, since the instruction itself is making it blatantly clear that you are incrementing the edx register. Comments should indicate the inner workings of the algorithm and/or provide information not otherwise immediately clear from the code and its context, rather than just rephrase what the mnemonics already show. So, the above could, for instance, be replaced by something like this:

inc edx {go to the next element in our product table}

Thirdly, you should avoid the use of slow instructions wherever possible. In general, the simple instructions are preferable over the complex opcodes, since on modern cpus the latter are implemented in microcode. Google for Agner Fog's publications on the topic of code optimisation, which discuss this and many other very useful aspects of how processors behave.

The final general principle is predictable: test your assembler routines thoroughly and continuously. For routines written in assembler, the compiler will produce substantially less warnings and error messages, and will offer no feedback with regard to the basic logic of the assembler code. Unused variables and wrong use of pointers will not be detected as easily as in Pascal code. So, prepare for intensive testing and debugging of your code. It will take more time and effort when compared to debugging regular Pascal code. That is yet another reason to keep these routines as short and readable as possible.

If after all of this, you still want to go ahead with writing assembler code for your Delphi/Pascal programs, reading this article is probably a good first step. I have designed it to be as generic as possible.

Next: Chapter 1: General Context of Assembler Code