316 points · by hahahacorn · 1y ago · 138 comments
A direct FFI call using JNI or the new foreign interface is fast, and has roughly the same speed as calling a Java method directly. Alas, the CPython and Java garbage collectors do not play nice, and require black magic in order to keep them in sync.
On the other hand, using proxies (such as in JPype or GraalPy) cause a significant performance overhead, since the parameters and return values need to be converted, and might cause additional FFI calls (in the other direction). The fun thing is if you pass a CPython object to Java, Java has a proxy to the CPython object. And if you pass that proxy back to CPython, a proxy to that proxy is created instead of unwrapping it. The result: JPype proxies are 1402% slower than calling CPython directly using FFI, and GraalPy proxies are 453% slower than calling CPython directly using FFI.
What I ultimately end up doing is translating CPython bytecode into Java bytecode, and generating Java data structures corresponding to the CPython classes used. As a result, I got a 100x speedup compared to using proxies. (Side note: if you are thinking about translating/reading CPython bytecode, don't; it is highly unstable, poorly documented, and its VM has several quirks that make it hard to map directly to other bytecodes).
For more details, you can see my blog post on the subject: https://timefold.ai/blog/java-vs-python-speed
- The Java side needs to store opaque Python pointers which may have no references on the CPython side.
- The CPython side need to store generated proxies for some Java objects (the result of constraint collectors, which are basically aggregations of a solution's data).
Solving runs a long time, typically at least a hour (although you can modify how long it runs for). If we don't free memory (by releasing the opaque Python Pointer return values), we will quickly run out of memory after a couple of minutes. The only way to free memory on the Java side is to close the arena holding the opaque Python pointer. However, when that arena is closed, its memory is zeroed out to prevent use-after-free. As a result, if CPython haven't garbage collected that pointer yet, it will cause a segmentation fault on the next CPython garbage collection cycle.
JPype (a CPython -> Java bridge) does dark magic to link the JVM's and CPython's garbage collector, but has performance issues when calling a CPython function inside a Java function, since its proxies have to do a lot of work. Even GraalPy, where Python is ran inside a JVM, has performance issues when Python calls Java code which calls Python code.
Go code and C code have to agree on how resources like address space, signal handlers, and thread TLS slots are to be shared — and when I say agree, I actually mean Go has to work around the C code's assumption. C code that can assume it always runs on one thread, or blithely be unprepared to work in a multi threaded environment at all.
C doesn't know anything about Go's calling convention or growable stacks, so a call down to C code must record all the details of the goroutine stack, switch to the C stack, and run C code which has no knowledge of how it was invoked, or the larger Go runtime in charge of the program.
It doesn't matter which language you’re writing bindings or wrapping C code with; Python, Java with JNI, some language using libFFI, or Go via cgo; it is C's world, you're just living in it.
https://dave.cheney.net/2016/01/18/cgo-is-not-go / https://archive.vn/GZoMKLike, talk over some queue, file, http, etc
Using IPC for all internal calls would probably take significant overhead; the user functions are typically small (think `lambda shift: shift.date in employee.unavailable_dates` or `lambda lesson: lesson.teacher`). Depending on how many constraints you have and how complicated your domain model is, there could be potentially hundreds of context switches for a single score calculation. It might be worth prototyping though.
There isn’t really a much more productive web dev setup than Rails + your favorite LLM tool. Will take time to earn Gen Z back to Rails though and away from Python/TS or Go/Rust.
Rails maybe was popular in the US at some point but it was always niche in the rest of the world.
All my new projects will be Rails. (What about projects that don’t lend themselves to Rails? I don’t take on such projects ;)
I am pretty sure this is the basis of the LuaJIT FFI: https://luajit.org/ext_ffi.html
I think LuaJIT's FFI is very fast for this reason.
I feel like I'm not getting something. Isn't ruby a pretty slow language? If I was dipping into native I'd want to do as much in native as possible.
In one major release, there was a bunch of Java code responsible for handling some UI element activities. It was found to be a bottleneck, and rewritten in C code for the next major release.
Then the JIT became properly useful, and the FFI overhead was more than the difference between the hand-tuned C code and what the JIT would spit out on its own. So in the next major release, they rolled back to the all-Java implementation.
Java had a fairly reasonably fast FFI for that generation of programming language, but they swapped for a better one a few releases after that. And by then I wasn't doing a lot of Java UI code so I had stopped paying attention. But around the same time they were also making a cleaner interface between the platform-specific and the general Java code for UI, so I'm not entirely sure how that played out.
But that's exactly the sort of see-sawing you need to at least keep an eye out for when doing this sort of work. Would you be better off waiting a couple milestones and saving yourself a bunch of hand-tuning work, or do you need it right now for political or technical reasons?
While this is suboptimal when doing one shot execution, when an application is long lived, mostly desktop or server workloads, this work pays off versus the overall application.
For example, Dalvik had a pretty lame JIT, thus it was faster calling into C for math functions, eventually with ART this was no longer needed, JIT could outperform the cost of calling into C.
https://developer.android.com/reference/android/util/FloatMa...
Most recently I did hand-looped matrix math and this ratio bore out.
I used gfortran, gcc, and python3.
I would also add that modern Fortran looks quite sweet, the punched card FORTRAN is long gone, and folks should spend more time learning it instead of reaching out to Python.
This is sometimes referred to as "self-hosting", and browsers do it a lot by moving things into privileged JavaScript that might normally have been written in C/C++. Surprisingly large amounts of the standard library end up being not written in native code.
But specifically with regards to library functions, like the other commentator said, losing out on in lining sucks, and crossing between JS and Native code can be pretty expensive, so even with things like sorting an array it can be better to do it in js to avoid the overhead... Eg esp in cases where you can provide a callback as your comparator, which is js, and thus you have to cross back into js for every element
So it's a balancing game, and the various engines have gone back and forth on which functions are implemented in which language over time
Example file for array.find(…): https://github.com/v8/v8/blob/5fe0aa3bc79c0a9d3ad546b79211f0...
If Ruby YJIT is starting to become a measurable factor (after all, it was slower than other, purely interpreted, languages until recently), then the same rule as above will become more relevant.
TL;dr - JIT rules.
If the FFI call can be made faster, maybe you can keep the loop in Ruby.
Of course that is attractive to people writing an application in Ruby.
That's how I interpret keeping as much code Ruby as possible.
Nobody in their right mind wants to add additional application-specific jigs written in C just to use some C piece.
Once you start doing that, why even have FFI; you can just create a module.
One attractive point about FFI is that you can take some C library and use it in a higher level language without writing a line of C.
When we optimize Ruby for performance we debate how to eliminate X thousand heap allocations. When people in Rust optimize for performance, they're talking about how to hint to the compiler that the loop would benefit from SIMD.
Two different communities, two wildly different bars for "fast." Ruby is plenty performant. I had a python developer tell me they were excited for the JIT work in Ruby as they hoped that Python could adopt something similar. For us the one to beat (or come closer to) would be Node.js. We are still slower then them (lots of browser companies spent a LOT of time optimizing javascript JIT), but I feel for the relative size of the communities Ruby is able to punch above its weight. I also feel that we should be celebrating tides that raise all ships. Not everything can (or should be) written in C.
I personally celebrate any language getting faster, especially when the people doing it share as widely and are as good of a communicator as Aaron.
Tcl had it’s web moment during the first dot com era within AOLserver.
Then just execute the c program with your flags or data in the terminal using ruby and viola, ruby can run C code.
How many programs have an https client in them because they need to make one request and didn’t know they could use curl?
I suppose if you could statically determine all of the bindings at boot up you could write a stub and insert into the method table. But, that still would happen at runtime, making it JIT. And it wouldn't be able to adapt to the types flowing through the system, so it'd have to be conservative in what it accepts or what it optimizes, which is what libffi already does today. The AOT approach is to write a native extension.
> you should write a native extension with a very very limited API where most work is done in Ruby. Any native code would be a very thin wrapper around the function we actually want to call that just converts Ruby types in to the types required by the native function.
I think our main disagreement is your assertion that any compilation at runtime qualifiees as JIT. I consider JIT to be dynamic compilation (and possibly recompilation) of a running program, not merely anything that generates machine code at runtime.
> Now, usually I steer clear of FFI, and to be honest the reason is simply that it doesn’t provide the same performance as a native extension.
I usually avoid it, or in particular, gems that use it, because compilation can be such a pain. I've found it easier to build it myself and cut out the middleman of Rubygems/bundler.
In libffi you built up descriptor objects for functions. These are run-time data structures which indicate the arguments and return value types.
When making a FFI call, you must pass in an array of pointers to the values you want to pass, and the descriptor.
Inside libffi there is likely a loop which walks the loop of values, while at the same time traversing the descriptor, and places those values onto the stack in the right way according to the type indicated in the descriptor. When the function is done, it then pulls out the return according to its type. It's probably switching on type for all these pieces.
Even if the libffi call mechanism were JITted, the preparation of the argument array for it would still be slow. It's less direct than a FFI jit that directly accesses the arguments without going through an intermediate array.
FFI JIT code will directly take the argument values, convert them from the Ruby (or whatever) type to the C type, and stick it into the right place on the stack or register, and do that with inline code for each value. Then call the function, and convert the return value to the Ruby type. Basically as if you wrote extension code by hand:
// Pseudo-code
RubyValue *__Generated_Jit_Code(RubyValue *arg1, RubyValue *arg2)
{
return CStringToRuby(__targetCFunction(RubyToCString(arg1), RubyToCInt(arg2));
}
If there is type inference, the conversion code can skip type checks. If we have assurance that arg1 is a Ruby string, we can use an unsafe, faster version of the RubyToCString function.The JIT code doesn't have to reflect over anything other than at worst the Ruby types. It doesn't have to have any array or list related to the arguments. It knows which C types are being converted to and form, and that is hard-coded: there is no data structure describing the C side that has to be walked at run0-time.
Yes it's probably worse than doing the jit in Ruby interpreter, since there you can also inline the type conversion calls, but there principles are the same.
Edit: This is wrong, see comments below.
Running in a debugger an ffi_call to a "int add(int a, int b)" leads me to https://github.com/libffi/libffi/blob/1716f81e9a115d34042950... as the assembly directly before the function is invoked, and, besides clearly not being JITted from me being able to link to it, it is clearly inefficient and unnecessarily general for the given call, loading 7 arguments instead of just the two necessary ones.
(the tramp.c linked in a sibling comment is for "reverse-FFI", i.e. exposing some dynamic custom operation as a function pointer; and its JITting there amounts to a total of 3 instructions to call into precompiled code)
But the C code is still going to be waaay faster than the Ruby code even with YJIT. That seems like an odd reason to avoid C. (I think there are other good reasons though.)
I can't find it but I remember seeing a talk where they showed examples of Ruby + YJIT hitting the same speed and in some cases a bit more than C. The downside was though that it required to some warmup time.
The YJIT website itself only claims it is around twice as fast as Ruby, which means it is still slower than a flat earth snail.
The benchmarks game has YJIT and it's somewhere between PHP and Python. Very slow.
I enjoy Ruby but activerecord is a mess and the language is slow and lacks real time functionality.
I'd still pick Phoenix over Rails any day of the week, but if I had to make the case for Rails, that would be it.
Most of the time these SDKs are just thin wrappers around their JSON API, so it's easy to build your own thing in Elixir anyway. And LLMs make it really easy. But it's something I've experienced pretty often.
Ruby has a first party external type definition format (RBS) as well as third-party typecheckers that check ruby against RBS definitions.
There is probably more use of the older, all third-party typing solution (Sorbet) though.
having to add annotations in a separate header file is simply too high friction to get widespread adoption.
edit: I am quite fond of `case ::Ractor::receive; when SomeClass then …; when SomeOtherClass then …; end` as the main pattern for my Ractors though :)
It definitely isn't at the level of Typescript adoption, even relatively speaking. And it's more clunky than Typescript. But it works well enough to be valuable.
There is also work to settle on an inline form of RBS so I could see it taking over from Sorbet annotations in the future.
> Crystal is statically typed and type errors are caught early by the compiler, eliminating a range of type-related errors at runtime.
> Yet type annotations are rarely necessary, thanks to powerful type inference. This keeps the code clean and feels like a dynamic language.
Why does it remain relatively unpopular and what can be done so that more people get to use it?
Because Ruby-ish syntax without Ruby’s semantics or ecosystem isn’t actually all that big of selling point, and if people want a statically typed language, there are plenty of options with stronger ecosystems, some of which have some Ruby-ish stntactic features.
Someone recommended me this, so I might even spread the word further https://github.com/soutaro/rbs-inline?tab=readme-ov-file#rbs...
If you're looking for static analysis in general, please note that there are mature tools available. Rubocop¹ is probably the most popular and allows for linting and code formatting. Brakeman² is a vulnerability scanner for Rails. Sorbet³ is a static type checker.
The tooling is there if you want to try things out. But, if you want a statically typed language then that's a debate that's been going since the dawn of programming language design. I doubt it's going to get resolved in this thread.
¹ - https://github.com/rubocop/rubocop