I wrote a program in C to generate fractals using a formula, but it goes very slow. Basically you pass the rendering function a bunch of unsigned char numbers that indicate functions to push values on to a stack or pop them off and perform and arithmetic operation and push the result back on the stack (kind of like reverse polish notation). The problem is, the program is reading these functions numbers, going through an if…else if…else if…else if…elseif… to find the right operation to perform, and pushing and popping a bunch of values for every iteration in every pixel. Normally there would just be a formula (like the Mandelbrot) hard coded into the rendering function, but this program is a DLL I’m writing to be an all purpose fractal renderer. Is there any way I could write a little mini compiler that reads the formula before rendering begins and compiles a function on the fly which could then be efficiently re-used by the rendering routine? After all, the whole point of Von Neumann architecture after all is that a computer can modify its own code.
Thanks in advance!
There is no notion of self-modifying code in C. Any attempt to pass control to a data block that is in the “data” memory, say, by casting a data pointer to a function pointer, is undefined behavior. This model is there to let you program in C for non vov-neuman computers.
This said, you can probably optimize your RPN code to run much faster by replacing sequences of if-then-else statements with function pointers or a switch statement. You could also program the target function into a dynamic library, read it at runtime, and use it in rendering.