 |
 |
DiscussionHeaven.comThe Best Place To Discuss On Any Topic |
|
|
Page 1 of 1
|
[ 1 post ] |
|
| Author |
Message |
|
tansolutions
|
Post subject: Programming tricks Posted: Thu Jul 23, 2009 11:26 pm |
|
Joined: Wed Jul 22, 2009 12:56 pm Posts: 69
|
Back on the Z80 chip, if you wanted to load zero into a register, you XOR'd the register with itself. It gave the right answer, the ones became zeros and the zeros stayed zeros. But why do it in this obscure way, when there was a "move" 0 to the register? The answer is that it only took one byte of memory, and it was faster. If your program had to do it a million times, you would really notice the difference.
You have seen this kind of expression in mathematics:
ax4+bx3+cx2+dx+e
In programming, that becomes one of these (depending upon the language):
a*x^4+b*x^3+c*x^2+d*x+e a*x**4+b*x**3+c*x**2+d*x+e
Or does it? The above are considered crimes in some circles. The following equivalent expressions are much faster:
(((a*x+b)*x+c)*x+d)*x+e e+x*(d+x*(c+x*(b+x*a)))
Which of the following is faster, in BASIC?
10 FOR I=1 TO 5 20 A(I)=I 30 NEXT I or 10 A(1)=1 15 A(2)=2 20 A(3)=3 25 A(4)=4 30 A(5)=5
The second one is faster. Of course, if you worried about speed, you probably wouldn't be programming in BASIC. But, you get the idea. The second one takes up more memory, and things like that are harder to read. So you have to decide what is more important. If this is inside a loop that must be executed millions of times, you probably choose the fastest executing code.
Addendum:
Some versions of FORTRAN did not allow the program to change the index of a do loop:
DO 100 I=1,10 I=I-1 100 PRINT I
This is a loop that will be executed ten times. But strangely, the programmer has decremented the index variable I, within the loop. And I remains 1, every iteration. And we have an infinite loop. In the version of FORTRAN that I used, this was illegal. I could not be changed within the loop. But there may be valid reasons for changing the index. In most languages, including most versions of FORTRAN, it is legal to change the index. You just have to be careful about it.
|
|
 |
|
 |
|
|
Page 1 of 1
|
[ 1 post ] |
|
Users browsing this forum: No registered users and 1 guest |
| |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum
|

|
 |