D
D
Daniel2021-01-22 14:31:47
Algorithms
Daniel, 2021-01-22 14:31:47

How to do an if check in a function only 1 time on the first call?

Suppose there is such a function in which it is known that only at its very first execution, the parameter can be null, then the if comparison will be meaningless.
The question is whether there is any approach, or optimization pattern.

void fun(string str)
    {
        if (str == null) /// после 1 выполнения функции, str != null всегда
            return;
        //// fast work
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Zagaevsky, 2021-01-22
@zagayevskiy

This is called "premature optimization". Checking for null costs nothing.

L
leremin, 2021-01-22
@leremin

And what's the difference whether to check the argument for null or for the first run?

W
Wataru, 2021-01-22
@wataru

Only write 2 functions: one with a check, the other without. And call the first one only the first time, and then the second. If the call is in a loop, then you need to expand the loop - pull out the first iteration before the loop and start the loop from the second iteration.
But this optimization will be practically useless in all cases. Stupidly increasing code can change cache hits and slow down your program much more.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question