242 points · by wagslane · 4y ago · 236 comments
> Using Java:
public static void sort(int [] a);
public static void sort(long[] a);
public static void sort(Object[] a);
Perhaps they meant it another way, but this makes it sound like there is runtime dispatch between these different signatures - there isn't. int, long etc. are unboxed types in Java, which are not Objects, and cannot be used for Object-based generic type-erasure. So the decision which of these sorts is going to be used is made by the compiler. All Objects are sorted using the third signature. public static <A> void sort(A[] e);
You will not be able to use the above method with an int[]. Whenever possible the compiler will try to be helpful, and automatically box/unbox primitives for you, so for example the following will work public <A> A max(A a1, A a2);
/* ... */
void foo() {
int x = max(1,2);
}
this comes at the cost of boxing ints inside Integer, though.So, if you ignore for a moment primitives types, whenever you have generics, everything boils down to a single method accepting Objects and returning Objects. What the JVM does is to do runtime profiling of what actually you are passing to the generic method, and generate optimized routines for the "best case". In theory this is the best of the two worlds, because (unlike, let's say, C++) you will have a single implementation of the method, avoiding code explosion, but if you use it in an hot spot you get the optimized code.
In a way, it is quite wasteful, because you throw away a lot of information at compile time, just to get it back (and maybe not all of it) at runtime through profiling, but in practice it works quite well.
A side effect of this is this makes the JVM a wonderful VM for running dynamic languages like Ruby and Python, because that information is _not_ there at compile time. In particular GraalVM/Truffle and exposes this functionality to dynamic language implementations, allowing very good performance (according to their website [1][2], Ruby and Python on Truffle are about 8x faster than the official implementation, and JS in line with V8)
[1] https://www.graalvm.org/ruby/ [2] https://www.graalvm.org/python/
I’d say the best situation would be keep the type information at compile time but let the VM decide if multiple implementations are needed or not at runtime.
But then you would probably need to cover just how aggressive the JIT is in the JVM and how the costs may not be what you would think they are.
The negative consequence of being ad hoc is that there's not even a very strong implication beyond the name that these different functions all do the same thing, and sure enough they often don't. So now either your users must read your documentation very carefully, or sometimes they will have unhappy accidents. This is made worse in many modern languages with type inference where your users may be mistaken about which of the functions they're actually calling since they don't always know the type of anything anyway...
Ad hoc polymorphism is over-used because it is relatively cheap to implement, and it's cheap to add more of these overrides later.
So generics are completely a language semantic concept in case of Java, with no performance detriment/benefit. Of course more information can be used up for better optimizations as well, see Rust’s or C++’s generics/templates.
For example
void <T extends Foo> bar(T f);
will, under the covers, create a function that looks like void bar(Foo f);
If you create a class class Foo implements Supplier<Bar> {
Bar get() { return new Bar(); }
}
The method signature for `Foo` does in fact return a `Bar` type and not some `Object` type even though `Supplier<Bar>` would imply that is erased. The same applies to if that generic was used within the method parameters.That generic type information is, in fact, stored off at the class level and can be extracted through Java's reflection API.
This is how magic like
json.parse("[1,2,3]", new TypeReference<List<Integer>>{});
is getting it's stuff done. It's creating a new anonymous class of "TypeReference<List<Integer>>" which the json library can then use to introspect and pull the generic information out and know that it should create a `List` of `Integer` rather than of `Long` or `Double` or a `Set`.This makes generics more than just a syntactic construction in Java.
https://docs.oracle.com/en/java/javase/17/docs/api/java.base...()
Edit: sibling comment by cogman makes the case more thoroughly.
Edit: also HN mangles the link to Class.getTypeParameters()
For what it's worth, this seems to be a common misunderstanding where generics are concerned.
Your method signature may look like
void foo(Iterable<Bar> b)
which would make you think of vtables and casting performance losses.However, Java's JIT is fairly cleaver. It can tell that you always call `foo` with an `ArrayList` and it can tell that `ArrayList`'s iterator always emits a `Bar` Object. From there it can elate a lot of the type tables and virtual dispatch to just be direct dispatch. It does that at the cost of a couple of added runtime checks to make sure those assumption's aren't violated.
The impact of generics on performance has, for me, generally been pretty low. I've seen a much higher impact due to java's memory model (which is getting fixed with Valhalla).
This, btw, is how JavaScript's and indeed most high speed JITs function.
Just to be pedantic int[] and long[] are both objects, but will be sorted using the first two signatures because the JVM uses different instructions for loading and storing elements from an array. Technically you could make a single function to return an array's length since it uses the same instruction.
Arrays are usually still preferred over collections in the case of primitive types (int[] etc.).
In the unlikely event that I'm modeling something that can be represented as a list of integers AND it's a significant performance bottleneck then, sure, I'll consider the array methods. But I don't recall the need arising in the last year or two.
Enterprise Java stuff just isn't often bottlenecked on that sort of thing. Network latency fills far more of my dreams ;)
A virtue of C, in my opinion, is that it's very difficult to accidentally bloat the code. C code tends to produce smaller binaries, while leaving the option of expanding performance-critical code sections with macros in cases where it is beneficial. It's much more difficult to take a heavily-templated C++ binary and shrink code size in the cold parts of the binary (which is probably most of the binary).
I agree there's nothing particularly terrible about the preprocessor as such, if used tastefully. Especially if you compare it to other macro engines like maybe TeX, CPP strikes me as quite simple and clean.
Even newer languages like Haskell choose to adopt it after all.
> the type-specialized code is larger in code size, which can cause its own performance problems due to icache.
since IIUC you mean the alternative would be essentially non-reified types, so the icache would involve more frequent branches, thus blowing cache in general, even with branch prediction.
anyway i'm pretty sure i'm missing your point, so figured may as well ask.
Each of these copies requires space for the instructions...this means a larger binary on disk, more memory required when it runs, and more pressure on the CPU's caches, especially precious L1I.
The cache pressure issue is typically the big one worth thinking about, although binary size itself can be an issue for some cases - I've primarily got embedded use cases in mind, but I'm sure there are others I'm not thinking of.
Anyway, back to cache pressure. If there are a whole bunch of different monomorphizations of a given function, and they're all called frequently, that could mean that the CPU will frequently need to refer to slower L2$, or much slower L3$ (or much much slower RAM) to load instructions. That's no bueno from a performance standpoint.
Because of this, there are cases when dynamic dispatch can outperform monomorphization - it's definitely not as simple as "vtable slower, monomorphization faster" across the board, even if that is an OK rule of thumb.
Another aspect about this is that the cache will hold the _hot_ stuff. In most systems, even if you have three copies of a function, it will likely only have one of those that is hot.
There are other libraries that do the same, another one was posted here recently. And of course, if needed, it can be implemented by the programmer. IMO the issue with the given Postgres example isn't that it is written in C therefore it is slow, it is why it doesn't use all of C's features to make it faster (assuming there is a real performance issue here - it is very possible that the Postgres authors didn't consider it a real issue until now).
Right, but that's kind of missing the author's point, which isn't "things that are written in C are slow" so much as "because C lacks generics and has a relatively-inefficient standard library implementation based on function pointers, most implementations do not take the extra steps of 'using all of C's features' to do something faster (because it's a lot of work, and the standard implementation exists)".
It's mostly just an argument that generic-lacking languages make it easier to do something slower than something faster, and most people and projects follow the path of least resistance. That there are more efficient implementations available if you sink more effort into it isn't in dispute.
I think the issue the author is pointing out is that, in the real world, this real-life (fairly obvious) performance improvement was enough of a pain in C, that it was not done for 25 years.
In languages with generics, this improvement would have come for free. With C, yes you can do the improvement, but you have to do it by hand, and you have now to maintain and debug multiple versions of sort.
As i wrote in another reply, that might be one way to read the situation - especially if you want to create a narrative where languages like C without generics have inherent faults - but another way is that it was there for 25 years because it wasn't an actual problem in practice so nobody bothered to fix it until now.
You'll see database people jump through far bigger hoops to get much smaller improvements.
After all while the linked article's author seem to present it as a problem that it took 25 years for this to be fixed, another way to see it is that it took 25 years for this to be an issue for someone to bother enough to try and fix it.
After all, "zero cost abstraction" (aka "optimizer passes") works just as well in C as in C++ ;)
The actual advantage of generics isn't performance, but less (manual) code duplication.
> The actual advantage of generics isn't performance, but less (manual) code duplication.
Or type safety, since code duplication will often be shunned. And the benefit of type safety is there regardless of whether the generics implementation performs specialization.
In postgres' case the whole set of comparison functions isn't know at the compile time of the server - new types / operators can be added at runtime by extensions.
Hence the branches for the few most common/performance critical cases. I'd personally prefer if we gradually moved to C++ in postgres, but that'd not change that we'd need to have those explicit branches to benefit from a faster sort.
Of course it'd be a lot less annoying to implement in C++ - manually implementing templates with macro magic is many things, but not fun.
I'm not sure if specialization is a good argument for generics. Not everyone implements generics through full specialization/monomorphization, and then the performance benefits are not much more likely to emerge than with function pointers or vtables. And many JIT compilers can effectively specialize code involving indirect calls.
The problem is that it more work for the compiler. For example GCC has an early inliner pass that will exploit all easy "inlining" (like those provided by templates) to simplify the code and to expose more opportunities for later passes. On the other hand, indirect function inlining is only done at later stages. The effect is that indirect function call inlining is much less reliable and sometimes not as effective.
It's a bit brittle of course to depend too much on the optimizer, but the whole idea of "zero cost abstraction" in C++ also puts a lot of trust into the optimizer passes.
https://godbolt.org/z/zTe8jocsE
Now tell me I need generics for this to get optimized. (Generics are useful for type safety, which you can add using macros in C, but this is then ugly).
>Now tell me I need generics for this to get optimized.
Generics are explicit and reliably optimized. Implicit function pointer optimization is non-obvious and optimized unreliably.
Yes, you just compiled C code as C++. Actually write it as C++ (get rid of the void* mostly) and your program becomes a constant time evaluation: https://godbolt.org/z/5fedo8s5q
It feels like there's a lot of wheel reinvention going on, all the time. Especially with systems languages. Rust is the one that seems to "get it" (bite the bullet on syntax and learning curve, but give you reliable software that is pretty fast). I'm still waiting on Jai to be made public to see what is going on there.
This author is making the case in terms of improved performance, which I find interesting.
Ultimately generic typing is a way of better expressing the constraints of a program to a compiler, which means the compiler can do a better job of generating code for specific instances. The downside is that the compiler needs to generate code explicitly for each concrete instance of a generic function or type, which means that it takes more compile time and code size is larger.
Edit: I'd also like to point out that JIT compilers and sufficiently-smart AOT compilers can do this sort of inlining if they can prove that for any combination of run time types passed into a sort() they have the same comparison function and inline it as needed. That said it's the same (or higher) complexity as a generics system, with more pitfalls (for example, if they can't prove it but make a guess the sort function never changes, then get the guess wrong, they have to de-optimize).
If you have a layer of indirection (i.e., no genetics so you need to dispatch at runtime) then you wind up with an additional jump instruction.
While modern processors and branch prediction make jumps relatively cheap, they can’t avoid instruction cache misses if the dispatch is happening frequently.
By removing the layer of indirection, the compiler can choose to inline the implementation instead of using a jmp; this keeps our icache clean, and can lead to faster execution.
However, there’s a real cost to this! Inlining is, in broad strokes, often faster; but that’s not always true if you’re e.g. inlining a large number of instructions into a tight loop. As with all performance, profile to know the truth.
PUSH x
PUSH y
CALL compare
CMP x y
POP
You end up with CMP x y
Of course this will vary based on the type that you're optimizing for but in all cases you're removing the need to push and pop the stack for every comparison. I'm not smart enough to talk about other optimizations enabled by generics though.Note, this is not just generics. Java could use overloading for years before generics to get similar benefits. Common LISP has type annotations that can give similar benefits. Generics is just a much easier/stronger to use construct for this in many cases.
Essentially, imagine you have custom routines for your ints and floats and your language doesn't support generics. You'll have a code like this
if type is INT:
answer = optimizedRoutineForInt();
else type is FLOAT:
answer = optimizedRoutineForFloat();
This happens at run-time. There's an overhead.With generics, there's zero overhead. Your code will look something like
answer = optimizedRoutine<Type>();
and if optimizedRoutine<Float> can be inlined at this site, there are no conditions or jumps in the code.The post goes in detail about how for sorting, this sort of comparison function is called so frequently it has a massive impact on performance
As an example, here's musl's qsort() implementation paired with a use in Godbolt. (I couldn't actually use LTO on Godbolt because it doesn't LTO the standard library, but the effect would be the same.) Note that there are no call instructions at all and the compareme() function is completely eliminated by the optimizer: https://godbolt.org/z/6W8Wxf6xP
That's true, but work to support them was already underway and when C# 2.0 shipped with generics, the bytecode and VM already supported it. That's why C# generics support specialization for non-reference types. Don Syme and company knew they wanted generics, but it takes time to design a system like that, so they shipped C# before that work was complete.
Even Fortran has added OO and generics.
This is anecdotal, but Java 5 adding generics was crucial for me to staying with a Java job. Without generics, working with generic algorithms and facilities was just miserable, and there was great temptation to use code generators based on some sort of templated Java as a workaround.
If Oracle were to disappear tomorrow I imagine Java would persist for quite a while as it's so embedded by now. It's the introductory language in schools across the US, so it's not going anywhere for now.
Go on the other hand I don't think would last very long (maybe a decade?) if Google decided to divorce themselves of the language, as it doesn't have the installed userbase of Java, but that's just my opinion. Who knows what would happen.
If instead you make the reasonable assumption that dynamic typing => pointer indirection, and look at how memory works in modern machines, it's also theoretically untrue for a huge number of programs.
All your 25 year-old projects will have performance bottlenecks to the extent you don't look for and address them.
The idea here that if you use generics your hot-path inner loops will be automatically optimized is nonsense. Yes, here and there you may get lucky -- the generics will exposes some code to an optimizer which will generate some great instructions without any extra work by you.
But while shaving a few bottlenecks off it nice, if your goal is performance, the bulk of the work is the same: you'll still have to consistently profile and optimize your code.
Also, if I'm reading https://go.dev/tour/moretypes/15 correctly, append is a variadic function and not a polymorphic function. That's something very different.
It is both variadic and polymorphic.
> Putting builtins on some special pedestal and demoting user-defined classes and functions is always a mistake IMO.
There is a line of thought in programming language design that claims everything should be user defined, but too much customization of everything inevitably leads to a lot of fragmentation, subtle incompatibilities and lots of ways to solve the same simple problem.
Avoiding all of these issues is an important part of go's reasoning behind some of their design choices and the proposed idea could probably fit that quite well.
That's only because the articles would be too long otherwise.
When I worked in a language without user defined generics I missed them all the time, and now when I work with Rust I use them all the time.
If you sit down and carefully write out the use cases for generics, which extend well beyond "parameterized data types", you'll note that Go interfaces cover a lot of them reasonably well, which is how it has been a viable language for versions 1.0 - 1.17. While this is an unpopular opinion, I don't really consider 1.18 to have "added" generics so much as completed them. (As evidence, consider how important "interfaces" still are in generics, and I can attest from personal experience with helping people that there's a lot of people who try to fire "generics" at a problem when they just need interfaces.)
I say this in support of the original post. Otherwise one must reconcile how Go could be successful "without generics"; my suggested resolution is that it shipped with "bad" or "incomplete" (more charitably) generics rather than no generics. Compare programming in Go with programming in C and the differences become very clear. There's a reason so many people were able to smoothly transition their code bases from Python to Go, for instance, which a view of Go in which it literally has "no" generics finds hard to account for. You need more than just "maps" and "slices" to do that successfully.
I’d argue that memory safety feels like more of a requirement but there are plenty of new languages which don’t have it.
The performance argument (for generics in statically typed languages) also feels weak to me.
Firstly, you can get lots of the same value of generics using polymorphism in a language like ML. E.g. sort might have a type like:
type ordering = LT | EQ | GT
sort :: ('a -> 'a -> ordering) -> 'a array -> 'a array
Which reads as ‘sort takes a function to compare things of some type 'a, and an array of such things, and gives you a (sorted) array of those things.’You can get type safety enforcing correct call sites (ie no sorting an array of strings with int comparison) and type safety in the implementation of the sort function however this could be implemented with (machine) code generated for the sort function only once rather than a separate function for each different type it’s used with. Indeed this is what you’ll get with the classic OCaml compiler. The thing you would want for performance is either sufficient inlining or generics which generate new code for each call.
So it seems that performance is not a necessary consequence of that sort of code generation. (Also you will get worse type checking with something like C++ templates because they are type-checked where they’re expanded rather than where they are created).
Secondly, this style of generics may lead to code size bloat which may lead to poor performance. Sure it is nice if you can speed up the functions in your critical path by 6% but if you have a big program doing lots of things, the increased number of cache misses/reads from having more code may slow you down. It’s maybe not great if e.g. you have a different function to peek inside a future/extract the value for each different thing you’d put in it, but that function would likely be inlined either way so isn’t a great example.
Found a bug though: the C qsort() comparison callback needs to be able to express a being less than b by returning a negative value. The post's returns 0 if equal or 1 if greater.
My typical implementation for numerical types goes
return a < b ? -1 : a > b; a <=> b
The 'spaceship' operator. You can sort an object by its foo property, then bar property, with: sort { $a->foo <=> $b->foo || $a->bar <=> $b->bar } @array;
Python is still better IMO: sorted(array, key=lambda x: (x.foo, x.bar))There can still be reasons to define all the operations explicitly, but those are rarely encountered.
Even further aside, in discussing language features and design, the expression "but those are rare" comes up frequently. For different languages, its meaning may be radically different. In C++, it means "for that case, you have to do something a little less convenient". For almost all languages, it means "we don't handle that case, you're on your own". That depth is what has kept C++ on top of the performance and major system implementation heap for decades, not just, as is often asserted, inertia. Achieving depth takes decades.
return (a > b) - (a < b);Are Generics a solution to a problem caused by programming in OOP?
Can someone explain what people did to solve these problems before someone came up with generics?
Thank you!
Maybe the best example of a language without generics is C. In short there are 3 solutions to counter the lack of generics: copy-paste the same code multiple times with minor changes, make this copy-paste automatic with macros, or circumvent the problem by further abstraction.
Let’s say you want to create a vector data structure that can grow. It is not a hard thing if you know the size of each element, so you can trivially write it for, say, ints. Now you want to reuse your logic for your custom structs that have a different size - the only change you would have to do is replace the element_size constant and repeat the whole thing with a different name (first solution). You might try to write some ugly hack with C’s pre-processor macro to generate this thing for you by an easier to use wrapper, or you could just implement a wrapper that has a next, prev pointer and use a linked list structure (with very bad performance compared to storing the elements next to each other in an array). C code often uses the third option due to the inconvenience of the first 2, which would be solved by generics.
Thank you for the response!
Like many things in programming, when your language didn't have a feature you just did it yourself. You didn't have one sort() method you had a different one for integers, floats, strings, etc. Or you used other language features that could accomplish the same thing only a little messier.
What it can't do is vary details of the implementation, at compile time, according to properties of the types operated on. C++ can do this. Rust can, to a degree. Go cannot, because it doesn't understand much about types. C macros cannot, because the macro system has no conception of types at all. The C optimizer can apply what it knows of types, but you have no way to tell it any more than it can puzzle out for itself.
If you are not used to a language that really supports strong types, you probably don't understand how much of programming work is offloaded onto the type system when using such languages. The C-grade "type checking" such languages provide is just the most trivial possible use of compile-time types. A powerful type system makes a language able to do automatically what you almost always cannot afford to do at all in a language without.
#define SORT_ELEMENT_TYPE int
#define SORT_COMPARE(a, b) sign(a - b)
#include "specialized_sort.h"
And the header would define a function with the following signature:
int sort_int(int[] a, size_t n);
But generics provide another benefit: in theory with them, the compiler should be able to determine that two high-level types are actually the same machine type, so in the above example, SORT_ELEMENT_TYPE int and long would not generate duplicate code on many machines.
I don't know what the implications are for Go with generic types. Either they've convinced themselves that a fast generic capable compiler is possible or the the compiler performance goal is no longer the high priority it once was.
public static <T> void sort(T[] array);
It is not often mentioned on HN that whole swathes of functionality modern C++ coding relies on are entirely missing from Rust. Clearly, people can get along without powerful features -- important programs are coded even in C -- but it is a great deal more work. One consequence is that C++ and, to a degree, Rust programs are faster than programs coded in weaker languages, simply because more time is available to pay attention to performance, and any such attention to a library may help many more programs. Weaker languages are simply unable to express usability improvements and optimizations you would like to capture in a library.
If I understand correctly, this is done with traits in Rust. In this case, the PartialOrd and Ord traits. More elaborate use cases for traits cover things like "is this type safe to send between threads" and "does this type have a statically known size on the stack".
C++ concepts are just duck typed, whereas Rust's traits have actual semantics.
For example in C++ a float (the 32-bit floating point type) is std::totally_ordered because it has the necessary operators so "quack" - even though of course this type isn't actually totally ordered. If (when) you rely on this sort of promise your C++ program is "ill-formed, no diagnostic required"...
In contrast Rust's 32-bit floating point type f32 is not Ord, because well, it isn't totally ordered is it? NaN. So sort() doesn't work on say a slice of f32, because sort is defined over totally ordered types. You will need to provide an ordering function to explain how you think they're ordered.
C++ had no choice, you can't show up decades late to the party and say "Now we're defining these semantic traits" when there's so much code out there without them. Rust started from a fresh slate. Now, Nathan here (and many like him) would prefer to make a virtue of this necessity.
Once upon a time (before Rust 1.0) Rust did actually have a trait named RandomAccessIterator but it was not well loved because it wasn't practical to do the optimisations you'd actually want (they'd be unsafe, and an unsafe trait here is a big pain point), yet without them it was too slow to be reasonable to suggest anybody use it. So it was abolished.
In practice the slice type [T] is fine here, and the Ord constraint means this sort, like the real one defined on slice, enforces the requirement you'd actually expect.
The Rust sort() implementation is safe here too, unlike the C++ one. It is also stable, because Rust chooses to give you a stable sort, and have people who know they need it write sort_unstable() when that's what they meant, whereas C++ assumes you'd better know exactly what you need or else too bad here's an unstable sort by default...
qsort is the prime example why (when!) generics do not matter. Half of the time if you need to sort, you're doing something wrong and the data should already be sorted (that's a sort in constant time). If that is not the case, but performance matters (which is quite unlikely by itself, since sorting is probably not where your program spends its time), then it is extremely likely that it's easy to write a much quicker sort than poort std::sort by taking advantage of the context. For example, some bucket sort which you could say runs in linear time.
The time spent waiting for bloated C++ templates to compile can instead be used to implement a sort routine that beats std::sort for the specific situation, and to improve on it 12 times over.
There is yet another point that is frequently heard, which is that compilers can inline function pointers if the "qsort" is defined as static inline. I'm only not sure how to guarantee that the inlining is performed.
To me this goes mostly to show that most people that whine about generics & performance don't know a lot about performance.
Generic sorting is something all programmers are familiar with so it makes good examples.
Kinda like the Dog->Animal inheritance hierarchies to prove why OOP syntax is required.
OOP is rarely the right way to organize a program, but almost any sufficiently large program has one or more subsystems that map naturally to OOP. A language that supports it is helpful in those places. Saying you could code the same thing without the feature wholly misses the point: of course you could, but it would be more work, and there would be more places to make mistakes.
The same applies to any powerful language feature. Where it is useful, using it helps. Where it is not useful, another may be. Languages lacking powerful features make the programmer do more work, leaving less time and attention to make the program, or other more important programs, better.
> Half of the time if you need to sort, you're doing something wrong and the data should already be sorted
OP is literally talking about the C implementation of Postgres. He probably needs to sort.
When you bulk insert into indexed columns, it sorts the inserted data and merges that with the existing index. If you do joins on non-indexed columns it often sorts the intermediate results.
Seems like this case is falling in the other half then.
Really it is almost everyone who doesn't know a lot about performance. Any modern programming language is targeted not at an expert, but a beginner(look at Rust which is supposed to be relatively difficult, yet is quite quick for people to pick up in my experience).
Languages should be able to be performant, even when used in poor ways. No matter what, people won't presort their data, since it likely comes from some database or csv file or json response or who knows what. So a language should be trying to accommodate that use case.
- construct sets
- remove duplicates
- construct and query dictionaries (especially multi-maps, btrees, etc)
- group equivalent elements
- find the number of occurrences
- etc
Hashing solutions tend to be popular in modern language standard libraries, but not in C or C++ where in-place algorithms and simpler implementations are preferred. You could also make the argument that it's much harder to use hashes with generics as it's not always clear how to define good hashes for complex data types. Alternatively, sort requires only a < implementation.
> bucket sort which you could say runs in linear time.
This only works for integers in a small range. Also consider strings, doubles, or lexicographically ordered arrays.