http://www.perlmonks.org?node_id=1225290


in reply to Re^2: Inline CPP undefined subroutine
in thread Inline CPP undefined subroutine

Now that the question is considered solved, this piece of code might serve as an interesting side note about (premature) optimization.

I was going to observe that ord('C') = 0x43 and ord('G') = 0x47, so you could do the comparison in one step (if (*gcString | 4 == 'G') or if (*gcString & 0xFB == 'C')), and perhaps compare 8 bytes in one go by casting the char * pointer to uint64 * and doing the necessary accounting.

Then it occurred to me to check the code the compiler actually generates from the simple and readable function above. There is a nice online service at godbolt.org that lets you do exactly that. Paste the function text into the source window (and add the necessary #include <cstring> header to make it compile), enter -O3 for compiler options, and behold. GCC 8.2 not only notices the similar ASCII codes and uses a trick similar to mine, but it generates an efficient but nearly unreadable main loop using SIMD instructions that compares 16 bytes in one go (which is better than what you can do with simple, standard C).

I also had the idea of replacing the loop in the function with while (*gcString++), thinking that strlen needlessly scans through the string once to find the terminator, but guess what - this kills the optimization. It needs to know the length in advance to be able to do the advanced SIMD loop.