Operator speed and recursive calls
Hi Will:
As a general rule, division is the slowest math operation you can do. If you want to experiment, try writing a tight loop that divides a floating point number by 10 a million times and time it. Then write the same loop and mutliply it by .1 a million times. While I haven't run this experiment for some time, the divide used to be about twice as slow. Perhaps new optimizing compilers are better now, but my guess is that division is still the slowest operator. Bit shifting was an old assembler language trick to do quick divides and multiplies by two, but that's probably an H-bomb to kill an ant now.
Methods and functions can call themselves in what is called a recursive function call. You might Google that for some explanations. Calculating a factorial is a classic example of recursion. Keep in mind, however, that each recursive call places a new set of parameters on the stack during each function call, driving the stack deeper and deeper. It's not uncommon to run out of stack space and crash the system if you don't code the terminating criteria correctly.
Anyway, it's encouraging that you're experimenting...it's a great way to improve your coding skills.
__________________
Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)
|