# How to optimize this branching instruction?

I have an outline shader, which samples my texture 8 times to compute the outline.

The problem is, that there's transitional alpha values between picture and background. To cut them off I'm using the following function instead of just sampling my texture by calling texture2D().

vec4 texSample(sampler2D sampler, vec2 pos)
{
vec4 color = texture2D(sampler, pos);

if (color.a < 0.5)
{
color.a = 0.0;
}

return color;
}


The question is: are there any ways to optimize this check or even avoid it at all?

There's really not much room for optimization here, having divergent branches over such a small if body is probably not affecting your performance really at all.

You could use something like discard which might convey your intention better, but ultimately will not change your performance.

Taking from this post, here's an example usage.

if (color.a < 0.5)
{
}


As a final side-note, if this shader is causing you performance issues you should look somewhere besides the shader. There's really nothing wrong here. You could make sure you're properly using mip-maps, I think that's a common source of slow down in OpenGL-ES because they're not generated by default.

This post has a link to a tutorial on mipmaps and how to generate them.

Use the built-in glsl function step to set any alpha value below 0.5 to 0.0.

color.a *= step(color.a, 0.5);

• Is this actually correct? color.a = 0.25 in the OP gives 0 but in this solution gives 0.5. Additionally is this even faster? When the threads diverge over the branch, in effect they're all executing two instructions regardless of path, in this solution they're executing at least as much. – Alex Sherman Apr 19 '16 at 15:41
• Just realised i understood the question wrong. Edited. – cozmic Apr 19 '16 at 15:46
• OK but still this is as slow or slower right? It's now assignment, math operation and built in function whereas the OP is only conditional and assignment. – Alex Sherman Apr 19 '16 at 15:50
• I'm not too sure, i would actually assume you are right as the OP is not really creating multiple branches which would cause slowdown. What I read everywhere is, that built-in functions should be used if possibl. Also it depends on how many invocations of this are done per frame to even make a noticable difference. I haven't tested it though, it's just my assumption. You are probably good either way. – cozmic Apr 19 '16 at 15:56