title: Manage to unmanaged transition from second AppDomain is very slow
body: <p>The setup is as follows:</p>
  
  <ul>
  <li>Main app domain loads a number of unmanaged C++ libraries from a C++/CLI assembly.</li>
  <li>A second app domain loads those C++ libraries, but of course it is just getting hold of handles to the previously loaded libraries.</li>
  <li>I run exactly the same managed C# code in both app domains that makes use of the unmanaged C++ libraries.</li>
  <li>The C++/CLI assembly contains a mixture of managed and unmanged code.</li>
  </ul>
  
  <p>When calling into the unmanaged C++ libraries from the main app domain the cost of the managed to unmanaged transition is fairly negligible compared to the overall cost of execution. However, from the second app domain that did not originally load the libraries the cost of the managed to unmanaged transition becomes substantial; orders of magnitude larger. I know this because I have run ANTS performance profiler and this is what it tell me.</p>
  
  <p>There are some unmanaged static variables in the C++/CLI assembly, I've tried replacing them when a new app domain is created, but this doesn't change the performance. There would well be a bunch of hidden ones.</p>
  
  <p>What could be going on here? Why should the transition in the other app domain be so slow? Is there anything obvious to try to improve things?</p>
  
  <p>Some context: the code is running in a separate app domain for isolation and so that it can be torn down when things go wrong. It would be very good to keep it isolated from the main app domain. It would be possible to start a new process from which to run the unmanaged code, however this could be expensive as it may require a lot of data to be serialized and deserialized and the cost of bootstrapping everything in a new process is also fairly large. In the general case the cost of the serialization and the bootstrap will be much lower than the cost of the managed to unmanaged transition that I'm seeing, but there is a lot of messing around involved and it still slows things down a lot.</p>