How to Delegate Control from a String to a series of functions in C
This is a performance critical part of my android application, and I am using the NDK (c) to process a large bitmap array.
int blender(const char* blendMode, int c1, int c2, int amount){
int sob, sog, sor, soa, dsr, dsg, dsb, dsa = 0;
dsr = Argb_GetRed(c1);
dsg = Argb_GetGreen(c1);
dsb = Argb_GetBlue(c1);
dsa = Argb_GetAlpha(c1);
sor = Argb_GetRed(c2);
sog = Argb_GetGreen(c2);
sob = Argb_GetBlue(c2);
soa = Argb_GetAlpha(c2);
int src_alpha, mix_alpha, dst_alpha;
src_alpha = soa * ((255 * amount) / 100) >> 8;
if (!strcmp(blendMode, "normal")) {
PSD_BLEND_NORMAL(dsr, sor, mix_alpha);
PSD_BLEND_NORMAL(dsg, sog, mix_alpha);
PSD_BLEND_NORMAL(dsb, sob, mix_alpha);
}
else if (!strcmp(blendMode, "exclusion")) {
mix_alpha = soa / 255;
//.... it's not always just the 3 macros
PSD_BLEND_EXCLUSION(dsr, sor, mix_alpha);
PSD_BLEND_EXCLUSION(dsg, sog, mix_alpha);
PSD_BLEND_EXCLUSION(dsb, sob, mix_alpha);
}
~~~~~~~~~ X 20 or so blend modes ~~~~~~~~~~~~
}
Currently it's running this blender function on every pixel, and doing a switch (clearly inefficient)
also, it has to take the original command as a string (From json, and passed down through ja开发者_开发知识库va)
I can think of a couple ways to make it more efficient, but they all involve writing 2 giant switch statements. I would prefer to use 1 switch statement, or lookup if possible
Thank you!
Pretty nasty problem but I got a "hackish" idea.
If the 'blendMode' names are chosen nicely, you could compare only the first two (or three) letters of the strings. If there are multiple strings with same first letters, you could make a special case and compare first and third letter and so on.
This trick would make the code a lot faster than calling strcmp() all the time. Also inlining the compare function might help too.
Here is some code:
/* compares first two letters of the string */
inline int fast_cmp(const char *mode, const char *cmp) {
return (mode[0] == cmp[0] && mode[1] == cmp[1]) ? 1 : 0;
}
if( fast_cmp(blendMode, "no") ); /* for "normal" */
if( fast_cmp(blendMode, "ex") ); /* for "exclusion" */
In action: http://ideone.com/OiXS0
Ofcourse the comparisons could be written directly into if / else statements but it might get confusing. This can be fixed with small and nifty macro:
#define FAST_CMP(x, y) x[0] == y[0] && x[1] == y[1]
And here is the macro in action: http://ideone.com/NQFwW
This macro version is perhaps the fastest way to do the comparison.
精彩评论