mardi 27 septembre 2016

Helper functions: lambdas vs normal functions

I have a function which internally uses some helper functions to keep its body organized and clean. They're very simple (but not short), and could be easily inlined inside the function's body, but I don't want to do so myself because, as I said, I want to keep that function's body organized.

All those functions need to be passed some arguments by reference and modify them, and I can write them in two ways (just a silly example):

With normal functions:

void helperf1(int &count, int &count2) {
    count += 1;
    count2 += 2;
}

int helperf2 (int &count, int &count2) {
    return (count++) * (count2--);
}

//actual, important function
void myfunc(...) {
    int count = count2 = 0;

    while (...) {
        helperf1(count, count2);
        printf("%d\n", helperf2(count, count2));
    }
}

Or with lambda functions that capture those arguments I explicitly pass in the example above:

void myfunc(...) {
    int count = count2 = 0;

    auto helperf1 = [&count, &count2] () -> void {
        count += 1;
        count2 += 2;
    };

    auto helperf2 = [&count, &count2] () -> int {
        return (count++) * (count2--);
    };

    while (...) {
        helperf1();
        printf("%d\n", helperf2());
    }
}

However, I am not sure on what method I should use. With the first, one, there is the "overhead" of passing the arguments (I think), while with the second those arguments could be (are them?) already included in there so that that "overhead" is removed. But they're still lambda functions which should (I think, again) not be as fast as normal functions.

So what should I do? Use the first method? Use the second one? Or sacrifice readability and just inline them in the main function's body?

Aucun commentaire:

Enregistrer un commentaire