Skip to content

Repository files navigation

ObjectCloner

Build statuscodecovNugetGitHub

ObjectCloner aims to be the fastest, yet most capable deep (or shallow) clone solution for .NET objects. It utilizes compiled Expression Trees under the hood, making it just as fast as (or faster than) a hand-written DeepClone method.

Features

  • Native speed using code generation
  • Works on any type
  • Does not require a parameterless constructor or custom attribute
  • Clones properties
  • Clones read-only fields
  • Preserves reference equality in the tree1
  • Handles circular dependencies
  • Handles polymorphism2
  • MIT license
  • 100% test coverage

1 For example if you put the same object into an array 3 times, you will get back a different list which also contains the same single clone object 3 times.

2 Interface-typed fields (IEnumerable, etc.) will be cloned using their actual runtime types.

Installation

The package is available from NuGet as ObjectCloner and maybe ObjectCloner.Extensions (see Usage). Install via the package manager console: PM> Install-Package ObjectCloner the dotnet command line: dotnet add package ObjectCloner or using your IDE's visual NuGet tool.

Usage

The library exposes a static class with two generic methods, making the usage very straightforward.

varclone=ObjectCloner.DeepClone(original);

or

varclone=ObjectCloner.ShallowClone(original);

If you would rather use an extension method format and don't mind polluting your object type install the package ObjectCloner.Extensions as well and use it like so:

varclone=original.DeepClone();

Performance

In a benchmark cloning a custom class hierarchy ObjectCloner beats every traditional solution except custom written cloning code.

MethodMeanErrorStdDevRatioRatioSD
Custom Code88.71 ns4.242 ns2.826 ns1.000.00
ObjectCloner520.09 ns54.632 ns36.136 ns5.880.56
Reflection2,648.47 ns172.854 ns112.711 ns29.881.51
Newtonsoft.Json9,315.16 ns661.012 ns437.218 ns105.106.05
BinaryFormatter22,743.60 ns1,369.405 ns1,121.254 ns256.5210.89

You can find the benchmarks in the samples folder of the solution and run them yourself.

About

Insanely fast and capable Deep Clone implementation for .NET based on Expression Trees

Resources

Stars

65 stars

Watchers

5 watching

Forks

Releases

Packages

Used by

Contributors

Languages