Is Swap() overkill?

April 17, 2021

We are to create a function to do repeated things. One of them is swap.

From stackoverflow, I read this is an expensive operation with function stack and since this can easily be implemented, one should avoid writing this function.

I respectfully disagree.

Let’s take a look at the following Swap function

void Swap(int[] items, int at, int with)
    int temp = items[at];
    items[at] = items[with];
    items[with] = temp;

I agree that this function is very simple. There might be a performance penalty when this occurs frequently in a crazy loop.

My perspective comes from readability. Without the function context, reading the above three lines (albeit it can be more cryptic with two lines with xor) in other code block, I will have to spend more energy to mind-map the three lines as swap. (comments can be placed to ignore, but that will add one more line to read.)

The same can be said for small functions such as Math.Max Such is simple that we can write the code in two different ways. I choose the one with the max.

bool Context1(int a, int b)
    if (a > b)
      return a > 200;
    return b > 200;

bool Context2(int a, int b)
    int m = Math.Max(a, b);
    return m > 200;
    // or return Math.Max(a, b) > 200;

Readability wins.

© 2023 Kee Nam