54
votes

My code approaches GLSL shader management in the way, that it creates each shader and the associated program and deletes each shader and program. I recently read http://www.opengl.org/wiki/GLSL_Object and there it is stated that:

The shader object, due to being attached to the program object, will continue to exist even if you delete the shader object. It will only be deleted by the system when it is no longer attached to any program object (and when the user has asked to delete it, of course).

Do I get this correctly, if I call glDeleteShader() on the shader object after linking to the program, I only need to track the program? Is it safe to assume this is always true?

4

4 Answers

63
votes

Yes -- in fact it is highly desireable to detach and delete your shader objects as soon as possible. That way the driver can free up all the memory it is using to hold a copy of the shader source and unlinked object code, which can be quite substantial. Measurements I have done indicate that NOT deleting the shader objects increases the incremental memory use per shader by 5-10x

13
votes

In general, the way shader object management works is simple. Shader objects don't really do anything, so there's no point in tracking them at all. Shader objects should exist for just long enough to successfully link a program object. After which time, the shaders should be detached from the program and deleted.

The above assumes that you aren't trying to use the shader object to link with a different program, of course. That's certainly possible. In that case, you should delete your shader objects after you have linked all of your programs.

6
votes

Yes. You can safely delete the shader then. In fact, this is the preferred way, because you have less maintenance. You need not keep track of what to delete, and you cannot forget to do it. And, it will still work.

"Deleting" the shader, as with all OpenGL objects, merely sets a flag that says you don't need it any more. OpenGL will keep it around for as long as it needs it itself, and will do the actual delete any time later (most likely, but not necessarily, after the program is deleted).

5
votes

In short: after glLinkProgram() call glDeleteShader() for each shader, this marks them for deletion and when the program is no longer needed call glDeleteProgram() - this call not only deletes the program but also detaches all shaders attached to it and deletes them (if not used by any other program).

So normally you don't have to ever call glDetachShader(). Read the docs for glDeleteProgram().