Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor LodePNG optimizations #173

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Conversation

woot000
Copy link

@woot000 woot000 commented Sep 18, 2022

LodePNG code size is decreased by about 1.5kB when compiled with MSYS2 CLANG64 Clang 15.0.0

Decoding (RGB and non-alpha grey colortypes) and encoding (any colortype) should be about 1-2% faster

A warning is fixed in lodepng_benchmark.cpp so it can successfully be compiled with the recommended build command

@@ -3256,33 +3256,28 @@ static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
if(mode->colortype == LCT_GREY) {
if(mode->bitdepth == 8) {
*r = *g = *b = in[i];
if(mode->key_defined && *r == mode->key_r) *a = 0;
else *a = 255;
*a = 255 * !(mode->key_defined && *r == mode->key_r);
Copy link

@zvezdochiot zvezdochiot Sep 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓ Why use multiplication where it is unnecessary?:

*a = ((mode->key_defined) && (*r == mode->key_r)) ? 0u : 255u;

Or use array?:

unsigned char wb[2] = {255, 0);
...
*a = wb[(int)((mode->key_defined) && (*r == mode->key_r))];

(for const time).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each conversion from if-else statement to multiplication in this case removes one jump instruction, creating code that has a few less branches and is also slightly smaller

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested this out with godbolt.org, and it looks like the way you write it doesn't matter, the effect is equivalent and it gets compiled to the same thing:

image

So the original with if/else looks more readable I'd say

Encoding speeds up by ~1% when compiled with -O3 on Clang 15.0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants