C# Object Constructor Vs Initializer Syntax Performance Difference Tested

When it comes to code readability, the initialiser syntax makes declaring C# objects very easy and clean to read. It also makes writing the code much faster since you do not need to be adding new constructors and lets you see what properties you have left to assign. But what about performance? Is one method faster than the other? I created some tests to see if the object constructor vs initializer syntax performance is difference is noticeable, here are the results.

To test this I created a console app with a stopwatch that would check to see the amount of time taken to declare an object using a standard constructor and time to declare using the object initializer syntax, aka using curly braces to declare an object.

I used the following code to do this.

	class Program
	{
		static void Main(string[] args)
		{
			var descriptiuon = "Longer description string for testing to see which type of object declaration method is the fastest.";
			var stopwatch = Stopwatch.StartNew();
			var test1 = new TestObject
			{
				ID = 1,
				Name = "test",
				Description = descriptiuon,
				Created = DateTime.Now,
				Updated = DateTime.Now,
				Number = 123456789012,
				Email = "[email protected]"
			};
			stopwatch.Stop();
			Console.WriteLine($"Test 1: {stopwatch.ElapsedMilliseconds}ms");
			stopwatch.Reset();
			stopwatch.Start();
			var test2 = new TestObject(1, "test2", descriptiuon, DateTime.Now, DateTime.Now, 123456789012, "[email protected]");
			stopwatch.Stop();
			Console.WriteLine($"Test 2: {stopwatch.ElapsedMilliseconds}ms");
			Console.ReadLine();
		}
	}

	public class TestObject
	{
		public TestObject()
		{

		}

		public TestObject(int id, string name, string description, DateTime created, DateTime updated, long number, string email)
		{
			ID = id;
			Name = name;
			Description = description;
			Created = created;
			Updated = updated;
			Number = number;
			Email = email;
		}

		public int ID { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
		public DateTime Created { get; set; }
		public DateTime Updated { get; set; }
		public long Number { get; set; }
		public string Email { get; set; }
	}
}

I ran the console app using Visual Studio 2017 and the result was a little surprising. 5ms might not seem like a lot to some, but when you are dealing with some code that does this millions of times, this is a big difference. I ran it a few more times and It varied between 2ms-5ms.

I wondered if this was just down to the order in which they were run and not to do with the method used. So I switched the tests around so that Test 2 would run first. If this tool 0ms and the other still took 5ms, then it would be a solid conclusion that using object constructors are faster than using the initializer syntax.

With the methods switched around, it shows that it doesn’t matter which method is used, it is the first one that takes the longest. After this point, all further declarations are instant. To be fully sure of this, I added a for loop that would run this code 100 times. Here is the output.

As you can see, the first call took 2ms and all subsequent calls were instant. At this point it is safe to say that both methods of declaring objects in C# are equally as fast. There is no benefit to using a constructor to declare your objects. Since it takes longer to write code this way, it is best to use the object initializer syntax when writing code.

Related Articles

Related Questions

How to Handle Unexpected 24/7 On-Call Duties?

I just got a new job and was surprised to learn that I'm expected to do 24/7 on-call support for the C-suite for one...

How can I access my old HDD on a new Windows 10 PC?

I built a new PC a couple of years ago, reusing some components from my old Windows 10 machine. Unfortunately, the external drive I...

How Can I Successfully Scrape Amazon Reviews Without Getting Blocked?

Hey folks! I'm having some serious trouble scraping reviews from Amazon using ScraperAPI, but it keeps getting blocked. Does anyone have suggestions on how...

2 COMMENTS

  1. This makes complete sense. With the object initializer you are assigning values to individual properties, which is far more calls than assigning multiple properties via a constructor. This is especially important if you’re assigning properties in an object in another layer.

  2. Nice. I thought the compiler would optimise the code anyway, wether using the initialiser syntax or not. Though I agree that the initialiser syntax is more readable, the debugging experience is not that great.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Latest Tools

Scavenger Hunt Team Randomizer

Planning a scavenger hunt and need to split participants into random teams? Whether you're organizing a school activity, a corporate team-building event, or a...

File Hash Generator Online – Get Instant MD5 and SHA-256 Hashes

Whether you are validating downloads, checking for corruption, or comparing files for duplicates, having a fast and secure way to generate file hashes is...

Visual CSS Editor for Modern Glass UI Effects

Modern UI design is all about clean, layered aesthetics, and few styles deliver this better than glassmorphism. If you're designing sleek user interfaces and...

Fast and Accurate Tap BPM Counter – Free Web Tool

Whether you're producing music, DJing live, or just figuring out the tempo of a song, knowing the BPM (beats per minute) can be critical....

Glassmorphism CSS Generator with Live Preview

Glassmorphism is one of the most visually striking design trends in modern UI. Its soft, frosted-glass effect adds depth and elegance to web interfaces,...

Add Custom Speech and Caption Boxes to Any Image Online

Creating comic-style images used to require complex design tools or specialist software. Whether you're making memes, teaching graphics, social media posts or lighthearted content,...

Latest Posts

Latest Questions