Hejlsberg Talk About Generics in C# and Java 128
An anonymous reader writes "artima.com has a very interesting interview with Anders Hejlsberg - the Borland guy now at Microsoft who can best be defined as MR C# - doing all the stuff that Borland wouldn't let him do. He discusses generics in C#, Java (1.5) and C++. Naturally there is the chance of bias but he does raise some interesting points againt Java's generics. Specifically that Java's genericised collections will have to box all primitive types as full objects, whereas C# does not. This is a big performance plus for C#. Java created the primitive types in the first place to address performance concerns but appears to be stepping sideways here. I can't help wondering if Sun has taken this approach to get the syntatic sugar in the language without requiring a bytecode change, but perhaps in a future VM version will allow primitive generics (obvioulsy forcing a bytecode regeneration)?"
Performance of generics (Score:2)
Do you have any references to back that up, or is this just "conventional wisdom"?
I'm not saying it's incorrect, but I'd wait until there are two implementations to compare.
Re:Performance of generics (Score:5, Insightful)
Just read a little further into the article. It seems that to avoid having to make changes in the VM, the Java generics have to become just like the current containers at the bytecode level. The main difference would be taht instead of having to type all the ugly type casts yourself, the compiler would do it for you. Obviously, this doesn't lead to any performance increases over Java 1.4 containters.
Compare this to, let's say, C++ templates, where the compiler makes a new copy of the template class specifically for each and every type you use on it. That makes the executable size increase a bunch, but it allows the compiler to pay the performance price, making the code perform almost like a program where a human programmer would have written a copy of the template class for each and every type you ever used it with.
Since the design of the java 1.5 generics is public knowledge, it's pretty easy for anyone with a reasonable programming knowledge to analyze it. It just seems that run-time efficiency wasn't the first thing in the designers minds.
Re:Performance of generics (Score:3, Funny)
pfft. right. Like I'm going to read an article before commenting on it.
Re:Performance of generics (Score:1)
Re:Performance of generics (Score:2)
Re:Performance of generics (Score:1)
You can get a very rough idea of the performance gain here [onjava.com] (scroll down to "Trove Primitive Collections"). It's a significant difference.
Of course, for most apps that people are writing for Java (i.e. webapps for business), an optimization of this magnitude won't be
Longhorn in C# (Score:1)
Maybe that's why it's not due until 2006: they have to wait for commodity hardware to get fast enough to run it responsively.
Re:Longhorn in C# (Score:1)
Boxing in Java (Score:3, Interesting)
Re:Boxing in Java (Score:2, Interesting)
So for instance if you have a List, you can not place an Integer with out unboxing it. Vice-versa, if you have a List you can not place an int into with out boxing it.
However if you have a List you can place an int into it directly without boxing it.
Re:Boxing in Java (Score:1)
So for instance if you have a List<int>, you can not place an Integer with out unboxing it. Vice-versa, if you have a List<Integer> you can not place an int into with out boxing it.
However if you have a List<int> you can place an int into it directly without boxing it.
Re:Boxing in Java (Score:4, Interesting)
I got the impression that C# could actually use generics to instantiate the array at type int, rather than type Integer with autoboxing.
Re:Boxing in Java (Score:1)
It will be neat, but it adds more complexity to the system.
Re:Boxing in Java (Score:2)
Yes, but complexity at the right place: in the compiler. Exposing the boxing/unboxing distinction to the programmer makes it easier to generate good code, but you now have all this manual wrapperized stuff to deal with all over your code.
On the other hand, research has shown that even naive analysis will allow you to generate quite good code from LISP, which is nominally completely statically type-opaque (you have no idea WHAT you have until you
Re:Boxing in Java (Score:1)
Generics is not like a recompile and go situation. You have to rewrite all your code that uses lists and collections if you want to use the new generic features, otherwise you get new compile errors when useing the collections. This is not as bad for C# as compared to Java since C# is a much younger language and thus the API is also smaller (so far).
Since in
Re:Boxing in Java (Score:1)
WTF are you talking about? The only way you're going to get an instance of a cl
Re:Boxing in Java (Score:1)
Should have been this:
Re:Boxing in Java (Score:2, Informative)
Since in
WTF are you talking about? The only way you're going to get an instance of a class that implements IList and only holds ints is to do this ArrayList intList = new ArrayList(); If you just choose ArrayList myList = new ArrayList(); yo
Class proliferation (Score:3, Insightful)
I mean, how many value types are there already? So you get a couple instantiatians of the class instead of one. And if you are really worried about footprint, you can use only reference types in your list.
Re:Class proliferation (Score:1)
Re:Boxing in Java (Score:1)
I never pass around collections outside of my own programming interfaces. Otherwise you have other problems.
Most of them relate to bounds checking and not type checking. Bounds checking which may change at runtime, rather then simple type checking which is rather static. I personally
Re:Boxing in Java (Score:2)
Nothing's changed here... (Score:2, Offtopic)
The Java collections operate this way right now (in JDK 1.4) and AFAIK have operated this way since the beginning. You can't add a primitive type to a collection, genericised or not, it has to be a first class Object. In terms of performance, whether or not the conversion is done explicitly or automatically shouldn't matter. If anything, the aut
Re:Nothing's changed here... (Score:3, Insightful)
Its faster because C# ints don't have to be converted. They are already objects (more like second class structure-like objects). When you define a collection of ints in C#, there is no boxing needed to populate the collection.
You are right about Java, however. The byte code looks the same if you use generics, or not. There won't be any performance loss from old code, just better looking code.
What the article is saying, is that adding primitives
Re:Nothing's changed here... (Score:2)
Yes, but the title of this article is "Generics in C#, Java, and C++". My question is, what the hell does autoboxing in Java have to do with generics? With generics, only objects can be put into collections. Without generics, only objects can be put into collections. Nothing's changed!
Of course, I think the real point of this article is to use the topic of Generics
Re:Nothing's changed here... (Score:5, Informative)
Both C# and Java require boxing if you want to put an int into an object variable. They differ in whether that boxing is automatic or not (at least until Java makes it automatic in 1.5), but that's irrelevant: it still happens, so the performance impact is the same in both languages.
However, if you're trying to put that same int into an ArrayList<int>, the two languages are very different.
In Java, ArrayList<int> is really just ArrayList<Object> under the covers, and stores its contents into an array of type Object[], so the boxing operation still needs to happen. Hence, there's a performance hit.
In C#, ArrayList<int> is interpreted as such at the runtime level and the JIT compiler creates native code for it that stores the contents in an array of type int[]. When you store values into that array, no boxing is needed, automatic or otherwise. No performance hit.
Both C# 1.1 and Java 1.4 collections can hold primitive types if you box them. In Java 1.5, you get some extra syntactic sugar (which C# had from day one) but the boxing still happens. In C# 2.0, generic collections can hold primitive types without boxing. That's the difference that he's trying to get across in this article, and why it's specific to generics.
All of this is explained very clearly in the article and it amazes me that so many people can't grasp it...
Re:Nothing's changed here... (Score:2)
The impression I got was that autoboxing was not necessary because everything is always boxed ( i.e they have no primitves in C# ).
Please correct me if I'm wrong.
Re:Nothing's changed here... (Score:4, Informative)
While "int" is treated "as if" it were an Object in the CLR, and behaves as if it was a subclass of Object, it really is a value type: It's allocated on the stack, cannot be subclassed, and is passed by value when it's used as a method parameter or return value.
The same goes for all the other built in primitive types (float, decimal, double, long, short, bool, char etc), along with user-defined Structs and Enums. These are all considered "Value Types" in the CLR.
When instances of value types need to be treated as Objects, they are boxed, just like in Java, except that it's transparent and automatic and there's no separate class that represents the boxed type - the distinction Java makes between int and Integer simply doesn't exist in C#. (System.Int32 is just an alias for int and isn't equivalent to Integer at all in any way).
The article clearly states that in Generic C#, the JIT actually creates specialized binary code whenever a generic class is instantiated with a value type argument. It even uses the example of List<int> turning into int[] (remember value types like int can't be subclassed, so the subclass problem doesn't arise).
C# provides the "illusion" of no primitives, but it's certainly not true that everything's always boxed. It just provides a more elegant and flexible model of boxing than Java does.
Re:Nothing's changed here... (Score:2, Insightful)
C# generics are smart enough to treat value types differently than reference types (or what you're calling a "first class Object"), while Java generics are not.
Why Generics? (Score:3, Interesting)
Re:Why Generics? (Score:2)
(who would have thought I need to use html entities in posting "Plain Old Text"?)
Re:Why Generics? (Score:1)
I think it's a marketing thing. Every now and again, the PHBs have a need to scream, "Look - we added new stuff"!!!
It doesn't really matter if the new stuff is useful or necessary, just so long as they can slap a "Now With 14% More Creamy Goodness" sticker on the side of the box.
Re:Why Generics? (Score:3, Insightful)
Because compile time errors suck much less than run time errors.
Re:Why Generics? (Score:5, Insightful)
Second, don't scoff at compile-time type checking - I've run into problems on large java projects where there's been some confusion as to what, actually, has been stored in certain collections. Generics prevent this.
It comes down to this: How much help do you, as a programmer, want?
Re:Why Generics? (Score:2)
Second, don't scoff at compile-time type checking - I've run into problems on large java projects where there's been some confusion as to what, actually, has been stored in certain collections. Generics prevent this.
I've run into this too, and you know what the solution is? To go to the programmer's cube who is responsible for the code and beat him/her with your clue stick until they wise up.
Re:Why Generics? (Score:1)
Re:Why Generics? (Score:2)
Who says they can? It just will make you feel better and release some stress beating the hell out of someone. Much better if he's responsible of something.
Re:Why Generics? (Score:1)
And no, I don't think that generics make it any easier to read the code
If someone hands you this interface.
public interface CrappyInterface {
public Map<String,String> getStringMap();
}
and tells you that their class implements it, what good has generics done you. Nothing. It buys you compile time saftey, sure, but what does the interface actually do? That requires documentation, and in the documentatio
Re:Why Generics? (Score:1)
List names;
then you don't know anything about what type to get out of that list. And if the coder had done something strange like put numerical references to a database with names in the list then you'll get a run-time error. If the list instead is
List names;
then you at least know something about what to expect from the List. (And you know that you have to hunt down documentation for it since it's n
Re:Why Generics? (Score:1)
The first example should read (as it does) List names;
The second example should read List<Integer> names;
Re:Why Generics? (Score:1)
Your attitude just doesn't scale.
Re:Why Generics? (Score:2)
Neither Java or C# can solve the problem of having too many people on the same project with bad management.
Re:Why Generics? (Score:5, Insightful)
The easiest response to that, is the point you just brought up. To get some semblance of compile time type checking, you'd have to make your own type. There are various disadvantages to this, among which are:
As for the benefits of generics, a basic one is that it makes the intent of the code clearer (since you don't want to make a custom type, for the reasons above). The other major one I can come up with right now, is making your interfaces clearer to people who would use your classes. By fully specifying the type (including what is supposed to be in collections), you can make sure the class user is clear on what the interface to a method is, and if he makes a mistake, the compiler will tell him. This means you don't have to deal with all the messy exception handling and such that would go along with just using Object base types.
I am agreed that the < > syntax can be too verbose at times, especially with something like LongClassName<AnotherName> foo = LongClassName<AnotherName>(). Of course, this leaves us with a quandary, since on the one had we want to be able to easily see and specify types of everything, which would suggest using full typenames everywhere. On the other hand, we could introduce typedef like functionality, but that would have some problems of clarity. It seems that Java has historically, and still is taking the first approach.
Re:Why Generics? (Score:1)
From your post, it seems that you're probably not working on a large (200K+ lines) application, where more than 3 or 4 programmers are involved in development.
If I could be the sole maintainer of all of the code in my project, I'd not see all that big of an advantage in generics. the main thing would probably be avoiding all of those ugly typecasts all java programmers have to live with, but all in all It'd not be a big deal. However, on a big project, I REALLY, REALLY want to be able to easily know which
Re:Why Generics? (Score:2)
It's a good thing then that you don't have to use generics if you don't want to. The choice is great, isn't it?
Personally I do a lot of development with the Java collection framework. Generics will save me a lot of time and code spent checking Object types.
Missing the point (Score:2)
Over and over and over again...
Bwahaha. Nice troll. Ask any serious programmer, and he/she will tell you that good coding practice calls for as many checks as possible during compilation, while it's still in the lab. "Whew, it got caught during ru
Re:Missing the point (Score:2)
Re:Why Generics? (Score:2)
I was assuming that the < >s would remove the need for the much dirtier
fooCollection.add(new Double(fooPrimitive));
and
fooPrimitive = ((Double)(fooCollection.get(xxx))).doubleValue();
etc.
Or is this still required?
Re:Why Generics? (Score:2)
Re:Why Generics? (Score:3, Insightful)
Sure you can. You can also write the Java bytecode by hand, in hexadecimal, using only your pinky fingers to type.
The point of generics is to reduce (significantly) the amount of time it takes to create strongly typed collections. In addition, it makes those collections more reusable. For example, if I make a strongly typed Iterator, either I have to make an Iterator that doesn't inherit from the java.util.Iterator inter
Re:Why Generics? (Score:1)
Speaking from personal experience, objects are used at least several times after being declared.
Re:Why Generics? (Score:1)
Seems reasonable... (Score:1)
It does seem any "performance" argument is bogus (Score:2, Interesting)
Re:It does seem any "performance" argument is bogu (Score:2)
When somebody says that a java application is painfully slow, the problem usually stems from the use of stock objects and the programmer's lack of understanding of
Re:It does seem any "performance" argument is bogu (Score:3, Interesting)
I disagree here.
Think of Moore's law, processor speeds, etc... Java is a fast enough language for doing just about anything a user needs to do. Even if java were only 25% as fast as native code, that would be 2 cycles of Moore's law, 36 months, 3 years ago. (And, java is much faster than 25% of C, check here [bagley.org])
3 years ago, users were a
Re:It does seem any "performance" argument is bogu (Score:1, Interesting)
But you're right about the G
Re:It does seem any "performance" argument is bogu (Score:2)
The slowness we're talking about isn't typically miliseconds, it's whole seconds. You're talking about graphical slugishness, which is a whole differen't issue, and one that most users don't even notice.
Re:It does seem any "performance" argument is bogu (Score:1)
Re:It does seem any "performance" argument is bogu (Score:2)
Now C# could in general be written better and do the *same* job faster. And I agree that this ability makes the language *better*. But saying this better feature of the languages is the *reason* it does something faster is bogus. I am pretty certain the artificial differentiation between primitives and objects in both languages is in order to make them more effic
Re:It does seem any "performance" argument is bogu (Score:2)
There are two types of collections: 1) collections of value types, and 2) collections of reference types.
Collections of value types are usually faster because they don't require: 1) individual heap storage for each element, and 2) dereferencing references to elements.
Java doesn't have generic collections of value types.
C# will potentially on-demand JIT compile many
Re:It does seem any "performance" argument is bogu (Score:1)
<oversimplification>So for example, an int[10] takes 40 contiguous bytes (4 bytes per int) on the heap. That block contains the actual values of the ints. An Integer[1
Re:It does seem any "performance" argument is bogu (Score:2)
Re:you, sir, are a retard (Score:2)
Let me reiterate: adding primitives should not slow it down, but I can think of no concievable explanation for it making it faster, so the slashdot writeup is wrong.
The possibility th
Re:you, sir, are a retard (Score:1)
This is not true at all. C# generics can be faster for primitives because the JITter compiles a separate native image when the type parameter is a primitive. It sounds like you thin
Re:you, sir, are a retard (Score:2)
Of course. That's why I said that it does not have to be slower. But that has nothing to do with whether C# handles non-primitives in a container faster. It may make them slower, or if correctly written it makes them the same speed. But it does not make them faster!!!
The only (good) reason Java doesn't support this in their impl of generics is for backward compatibility wi
Re:you, sir, are a retard (Score:1)
Though, AC poster at this level pointed out that the fact that the CLR does not erase the type information the way the JVM does could let you skip a cast. (Not likely to make much of a difference, IMO...)
I give up (Score:2)
Face it, Java does not do primitives in the containiers. It does not do them "slower", it just DOES NOT DO THEM!!!
Therefore C# is not "faster". It is instead, better designed.
And I would like it if somebody came up with a language
Can't Believe (Score:2, Informative)
Programming languages are tools. Hammers for nails, screwdrivers for screws, C for hardcore big stuff and python/perl for everyday fun. Java was never intended to be high per
Re:Can't Believe (Score:1)
I laugh when people make sweeping generalities that aren't based in reality.
The other downside to java generics is worse (Score:5, Informative)
What's more important is his other problem with Java generics which is that in runtime it's not possible to tell what type a collection is compiled as, this is to retain bytecode compatibility. So reflection will have no clue on any of this generics stuff, which isn't a deal breaker, it's just a downside I hadn't heard about before.
Re:The other downside to java generics is worse (Score:1)
I prefer the Java approach because it means my 1.5 Java code is compatible with pretty much every modern JVM out there.
I'm sick of trying to identify whether I have a user machine with
Re:The other downside to java generics is worse (Score:2)
He is wrong... (Score:2)
It seems many Slashdot readers not only fail to read the articles or others' comments, but can't even be bothered to read the whole little summary blurb before commenting.
Half the comments on this story ar
Oh, the irony! (Score:3, Interesting)
where it makes sense, but we are also very
conscious about not sharing where you want
the performance.
Welcome to the Microsoft business model. :)
C# vs Java (Score:4, Insightful)
But I keep coming back to the idea that the changes (or improvements) aren't enough. If you accept that all of the changes are improvements, that they make things better, they're still not enough to justify getting locked into a single vendor, or in learning new libraries.
C# cleans up some of Java's annoyances, which is great, but the annoyances just aren't big enough to make the shift worthwhile. That's the problem.
I think the libraries problem is huge for Microsoft. The java libraries are just getting to be so big, complex, and rich that it will be very hard to get people to move away from them.
I don't think that anyone says there aren't annoying things in Java, parts of it that wouldn't be done differently if the language could be redesigned from scratch. But those annoyances are liveable -- for the most part, you can deal with them.
Java's has those libraries, though, and one of the reasons the libraries are so rich is that Sun opened up the process to other companies. MS is huge, they have a lot of smart guys, but I just don't think they can compete with Java's comparative openness.
That's the thing -- you can read about checked exceptions, and agree that it would be nice if java handled things more like C#, but it's not even close to being enough to overcome the value of java's openness vs. Microsoft's closed approach.
In the end, it really comes down to the business model.
Re:C# vs Java (Score:2)
Re:C# vs Java (Score:3, Insightful)
But if I had a job writing software for large banks, or some other very serious group of people (I don't), I'd be afraid of using something like IKVM and Mono -- again, Java's annoyances don't seem annoying enough to push people that far out of the mainstream.
Isn't the primary value of these sorts of projects in the learning?
I mean, in order to follow the IKVM development blog, I'd have to be a much
Re:C# vs Java (Score:2)
I have some development tools [nongnu.org] written in Java which have language-independent output (supporting both Java and C#) but our company primarily uses C# these days. Still, every developer had to install the JDK and a JDBC driver in order to run our compile process, since it invokes t
Can you call C# from C++? (Score:2)
But Matlab has a cool way of using Java objects, and Java objects have a less-fuss connection to Matlab than MEX-C++. And for tight loops in pure numerical code, Java oddly enough is actually pretty efficient.
JNI al
Of what use are generics? (Score:1)
I've never used genrics. From what I understand, it's a way to keep a group of different objects in a collection without having to warry about what type of object they are when you retrieve them.
I can't think of any useful application where I need a collection of different types of objects. In some case where I might (a shopping cart) the items can just implement an interface to guarantee me the operations I need to perform on different objects.
Why would I need to collect a String, an int and some user-defi
Re:Of what use are generics? (Score:1)
Actually, I was going to give an example, but rather I will instruct people to RTFA.
Re:Of what use are generics? (Score:1)
Is that all? Seems like much ado about nothing.
Re:Of what use are generics? (Score:1)
That's not "much ado about nothing", it's just that you don't know what you're talking about.
C# and Java are getting generics because you don't want to spend three days inheriting from DictionaryBase or whatever to crate yet another st
Re:Of what use are generics? (Score:2)
Re:Of what use are generics? (Score:1)
A a = (A)list.get(0);
I'm still not getting it. It just doesn't seem to be that big of a deal to override the put() method to throw an exception if you try to insert something that doesn't implement your expected interface.
Of course, the rest of the posters to this thread wouldn't have had the opportunity to look down their noses at me and make condescending remarks but that doesn't seem
Re:Of what use are generics? (Score:1)
True, but this will generate a run-time error, while generics will generate a compile-time error. The run-time error will not be detected until the program actaully executes the code. This may make it necessary to do a lot of tedious testing, and you risk missing some special branch of the program which vio
Re:Of what use are generics? (Score:2)
Secondly, the easiest way to protect a Collection is to wrap it. That way you only cast and uncast in one place. It gets inlined, so no performance penalty. It also lets you change the data structure type at will. Say you want to change from a linked list to a dynamic array or a tree. It's simple, and great for fixing performance problems.
I don't recommend implementing the collections i
Re:Of what use are generics? (Score:1)
However, I sometimes wish Java stopped evolving all the time, it is getting so hard to keep track! We were doing fine without generics weren't we?
Re:Of what use are generics? (Score:2)
Re:Of what use are generics? (Score:2)
Re:Of what use are generics? (Score:2)
Re:Of what use are generics? (Score:2)
There are a couple ways to design containers. First you have have them hardcoded into the language like, but eventually someone will want a different way of storing data than the language provides, and will have to implement their own container. The next simplest
Not obviously forcing anything (Score:1)
Allowing primitive type arguments in generics would not necessarily require any changes to the VM or bytecode.
The Java 1.5 implementation of generics is substantially based on the Pizza compiler, which allowed primitive type arguments without requiring boxing (links: the pizza compiler [sourceforge.net], the GJ compiler it evolved into [unisa.edu.au], some academic papers about the compilers [lamp.epfl.ch]).
If I remember correctly
Re:Not obviously forcing anything (Score:2)
There *are* constraints on template types in C++ (Score:1)
Re:There *are* constraints on template types in C+ (Score:2)
So, you can't restrict by base class at compile time like you can with C#.
T
What he really is saying (Score:1)
BUT he is lying, it is actually the other way around. ;)
I don't understand what Mr. Hejlsberg is saying here. Does he imply that C# code is checked before you compile it, and the programmer is prevented from typing the wrong thing, using their super-secret-mind-reader-thin
Re:Denmark? (Score:1)
And of course Lego! If that's not pure Object Oriented thinking, then I don't know what is...
Re:Denmark? (Score:1)
It must be something in the water over there.