In my profiler reports I'm increasingly seeing the results of mock-based testing with dependency injection. Many of the dependencies were static, but because we want to test methods in isolation they are changed to instance members, like the following example:
class ShortLivedThing {
IDependency1 dep1;
IDependency1 dep2;
IDependency1 dep3;
...
int TheRealData;
// Constructor used in production
public ShortLivedThing() {
dep1 = new Dep1(); dep2 = new Dep2(); dep3 = new Dep3();
}
// DI for testing
public ShortLivedThing(IDependency1 d1, IDependency2 d2, IDependency3 d3) {
dep1 = d1(); dep2 = d2(); dep3 = d3();
}
}
In turn the dependencies most of the time have other dependencies and so on. This results in the instantiation of a tree of (mostly "static") objects every time a method call is done outside of tests. Each of the objects are very small (just a few pointers), but the tree effect turns this into an ever increasing performance hit.
What can we do about it?