Central Administration has a screen allow users to change the application pool identity, but doesn't allow you to change the application pool which the web application uses. You can modify manually by opening IIS, changing the application pool and making changes to the metabase.xml. But how do I make these changes programmatically?
Theory
An IIS Web Site in SharePoint is represented by the SPWebApplication class http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spwebapplication.aspx this has a property called ApplicationPool which allows to be retrieved and set http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spwebapplication.applicationpool.aspx.
Code
System.Uri webAppToChangeUri = new System.Uri("http://intranet");
SPWebApplication webAppToChange = SPWebApplication.Lookup(webAppToChangeUri);
webAppToChange.ApplicationPool.Name = "ALL MOSS";
webAppToChange.Update(true);
webAppToChange.Provision();
Demo
I ran this code inside a windows form, you can use this or a console application. The current application pool and the one I want to change it to has the same identity, so I just changed the ApplicationPool Name. If your identify is different you will need to set the Username and Password properties as well.
Before running the code the intranet web application has the following properties
After I run the code, right click IIS Manager and click refresh. I open the properties of the intranet web application and check the settings have came through.
That's it.
Why change the application pool?
For every application pool a w3wp process will be launched and can consume large amounts of memory. You need to find a good balance of isolation (provided by having many application pools) and consumption of memory. Have a look at Joel's article here http://blogs.msdn.com/joelo/archive/2007/10/29/sharepoint-app-pool-settings.aspx