Reputation: 1125
I wonder what is the best way to reuse the same shader multiple times. I have different Objects which use the same shader. Is it okay to compile & link the same shader for every object again, or should i better compile / link just once?
The question is: does OpenGL cache the compiled shaders or would they compiled again?
And how about linking: should I use one program multiple times for different objects or is it also okay to recompile multiple programs with equal shaders?
/** Option 1: Using same equal shaders multiple times **/
int vertexShader1 = loadShader(GL_VERTEX_SHADER, vertexShaderCode);
int vertexShader2 = loadShader(GL_VERTEX_SHADER, vertexShaderCode);
int vertexShader3 = loadShader(GL_VERTEX_SHADER, vertexShaderCode);
int program1 = glCreateProgram();
int program2 = glCreateProgram();
int program3 = glCreateProgram();
glAttachShader(program1, vertexShader1);
glAttachShader(program2, vertexShader2);
glAttachShader(program3, vertexShader3);
glLinkProgram(program1);
glLinkProgram(program2);
glLinkProgram(program3);
/** Option 2: Using same shader multiple times **/
int vertexShader = loadShader(GL_VERTEX_SHADER, vertexShaderCode);
int program1 = glCreateProgram();
int program2 = glCreateProgram();
int program3 = glCreateProgram();
glAttachShader(program1, vertexShader);
glAttachShader(program2, vertexShader);
glAttachShader(program3, vertexShader);
glLinkProgram(program1);
glLinkProgram(program2);
glLinkProgram(program3);
/** Option 3: Reuse program **/
int vertexShader = loadShader(GL_VERTEX_SHADER, vertexShaderCode);
int program = glCreateProgram();
glAttachShader(program, vertexShader);
glLinkProgram(program);
Upvotes: 0
Views: 703
Reputation: 162164
If in doubt: Minimize the number of objects and reuse. Switching shaders is amoing the more costly operations in OpenGL and relying on the driver to deduplicate is bad practice.
Upvotes: 1