简体   繁体   中英

How to optimize this Code

var type = typeof(TInterface);
        var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
            .SelectMany(s => s.GetTypes())
            .Where(t => type.IsAssignableFrom(t));

This code is going slower than I would like. Can someone suggest a more optimal way to code this in C#?

The ToList() is entirely redundant, although this is very unlikely to cause any slowdown:

var type = typeof(TInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Where(t => type.IsAssignableFrom(t));

FYI the above code should be relatively quick, its only at the point where you attempt to enumerate through types that the .Net framework does the heavy lifting.

Other than that there is nothing to be optimised without knowing more about what you are trying to do - the above gets an enumeration of all types t in all assemblies loaded into the current domain where typeof(TInterface).IsAssignableFrom(t) - if there are a lot of types / assemblies loaded then I'm afraid that this is going to take some time.

Can you tell us more about what you are trying to do?

You are iterating over all types in all assemblies you have loaded/referenced. But the type you want is your type so you know it isn't in any of the system assemblies. So for example you can filter out assemblies in the global assembly cache if you program isn't installed there:

var type = typeof(TInterface);
var types = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.GlobalAssemblyCache)
    .SelectMany(s => s.GetTypes())
    .Where(t => type.IsAssignableFrom(t));

You can use other filtering strategies to restrict the assemblies to your own if your application is installed in the GAC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM