0

Would there have been a difference in performance if C#'s built-in data types were implemented the same way that Java's primitive data types are implemented?

For example, in C#, if we write the following code:

int foo = 1;

we are declaring and instantiating an object, right?

However, in Java, when we write the same piece of code, we are not instantiating an object. Since 'int' is "implemented directly by the Java compiler and the JVM."

So I was wondering if it would have made a difference if C# had used the same implementation as Java -- i.e. by not making an object every time a primitive data type like int is used in C#.

  • 2
    You may find this interesting: https://stackoverflow.com/questions/436211/is-everything-in-net-an-object It is saying that though int is inherited from System.Object, and can act as an object, as far as memory is concerned that act like primitives, unless you unbox them – developer May 23 '18 at 16:54
  • 1
    @developer "unless you box them", surely... (contrast: "unbox them") – Marc Gravell May 23 '18 at 17:02
  • 1
    [Looks like nothing good](https://benchmarksgame-team.pages.debian.net/benchmarksgame/faster/csharp.html). In fact C# compiler knows what to do with primitive types, when in case of Java if you need a wrapper type like `java.lang.Integer` (usually for something Map) auto-boxing is something happening at run-time. – Victor Gubin May 23 '18 at 17:04
  • yes, sorry box not unbox – developer May 23 '18 at 17:11

1 Answers1

5

For example, in C#, if we write the following code:

int foo = 1;

we are declaring and instantiating an object, right?

Nope; you are declaring either a local value-type on the stack, or a value-type instance field. Zero objects were involved. int is not an object-type, and Int32 and int are the exact same thing in .NET.

(Actually, there is a scenario where foo can end up causing an extra object - related to how locals in some methods are handled; aysnc, iterator blocks, lambdas, etc.)

by not making an object every time a primitive data type like int is used in C#.

That's exactly what C# does, and has always done. More: unlike Java, this works with generics too.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900