0

I work on data processing which works with layered data.

The best analogy to my current work is that of network processing. Packets are layered and each layers is processed individually by a specicialized function. The next function to call for a deeper layer is calculated in the current layer. Under some circumstances it can happen that the callstack shows recursive behviour in a way that a previously called function is called again (eg. A()->B()->C()->B()->D()...)

Currently I do that in the following way:

void func_N(void)
{
    // get next layer info
    switch (next) {
    case A:
        func_A();
        break;
    case B:
        func_B();
        break;
    default:
        finalize()
    }
}

I can guarantee that the call chains do not become arbitrarily long. There is a technical limit, although pretty high. The depth of the callstack is dependent on the data which we can make some assumptions about. I'd need to get some fresh statistics, but a maximum depth of 10 calls would be a good estimate.

I hope you get the idea. Works fine, but the more complex the potential trajectories through the call stack become, the harder this gets to maintain.

However, maintainability is not my primary concern. In this case, performance is. Are there other, faster, better suited programming techniques for this problem?

flowit
  • 1,382
  • 1
  • 10
  • 36
  • Are you talking about state machine in some very cryptic way here? Or about recursion? – Eugene Sh. Jul 19 '18 at 16:13
  • I don't understand what you mean by "this problem". Is there a performance problem? Have you profiled your code? – n. m. could be an AI Jul 19 '18 at 16:17
  • `https://stackoverflow.com/questions/133214/is-there-a-typical-state-machine-implementation-pattern` maybe – mbieren Jul 19 '18 at 16:20
  • Create an array `struct { next_type_t next; void (*f_to_call)(void); } nexts[] = {{A, func_A},{ B, func_B},...};`. Then search in array of nexts the value of next and call the appropriate function. This is C implementation of map+interface abstraction and it's easier to maintain. You may interest yourself in state pattern from [here](https://stackoverflow.com/questions/4112796/are-there-any-design-patterns-in-c). – KamilCuk Jul 19 '18 at 17:03
  • You said that you can guarantee that call depth does not become arbitrarily long. Do you mean that it's guaranteed not to be infinitely long? Is there a known limit? – Jim Mischel Jul 19 '18 at 23:29
  • Yes, according to its definition that would be a state machine. You're absolutely right. I do not need to keep the state. I will implement the lookup table with function pointers and compare performance to the current implementation. – flowit Jul 20 '18 at 07:01

0 Answers0