As an optimization, a number of security demands may be combined into one by use of the following technique. If within a single method a number of operations are performed that all result in the same security demand by the underlying classes, by doing a demand and assert of the permission it is possible to reduce the overhead of the resulting security demands. Especially if the caller stack depth above the method is large this technique will result in significant performance gain.
Suppose a certain method is going to perform, say, 100 operations that require the X permission; of course to be allowed the code and all callers must have X permission. Without declarative security, each operation will require a stack walk of all callers to demand that X permission is granted, thus if the stack above X is n levels deep, 100n demands are required. The optimization is to first demand X that will do (depth n) stack walk to ensure that all callers indeed have permission X, and then assert permission X. Asserting X means that subsequent stack demands will stop at this method and succeed, reducing the number of demands by 99n.