• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 184
  • Last Modified:

Quickly Creating Objects in c# at runtime

I have a interface

interface IGetData
        List<object> getData(string classname);

Now my getData needs to get the data from a data source and populate the class object whose class name is "classname".  One of the ways to create the object is to use activator.createInstance. But creating 1 million objects at runtime would mean a lot of performance overhead. Is there a workaround for this problem by using generics etc.
1 Solution
Have a look at the code here

This is for cloning an object which including creating loads of objects as well as copying value in all of those. You can remove the part of the code which deals with cloning the elements.

Some explanation from that URL itself
The basic thing that it does is, create a DynamicMethod, get the  ILGenerator, emit code in the method, compile it to a delegate, and  execute the delegate.
The delegate is cached so that the IL is not  generated each time a cloning should take place, so we loose only one  time performance, when the first object is cloned (the IL has to be  created and compiled at runtime).

You will also have to consider if your datasource will be a bottleneck in the speed of creation of objects and you might have to try using threads for that.
Pass in a fatory object instead of a class name. Use the class name to create the factory object once, then use that object to create objects from the data. The key to using reflection (or activator calls) efficiently is to avoid doing it in tight loops.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now