194 points · by praseodym · 2y ago · 250 comments
Sure, some devices require using static memory allocations or are quite restricted. But a lot of other "system programming" targets far more capable machines.
There's a 3x speedup sitting in a library because it's in a sea of carefully optimized functions manipulating floats, and someone made a change to extract a function that returned an array.
It was such a good Chesterton fence: change seemed straightforward and obvious, better readability. But, it had cascading effects that essentially led to 9 on-demand array allocations in the midst of about 80 LOC of pure math.
In my experience, there's hangover from two concepts:
- Android does garbage collection and Android is slower than iOS
- You can always trade CPU time for memory and vice versa (ex. we can cache function results, which uses more memory, but less CPU)
There's a lot of things going on that make this the case.
Android was built with unrestrained multitasking; there's a lot of restraint now, but there's probably still a ton of stuff going on from unrelated processes while your foreground app is chugging along. iOS locks down background execution, and I suspect system apps have limited background execution as well. Less task switching and less cache pollution help a lot.
iOS only runs on premium phones. Even Apple's lower priced phones are premium phones. Android isn't necessarily quick on premium phones, but it can be much worse on phones designed to a $50 price point.
IMHO, A large issue is that the official UI toolkits are terribly slow. I'm more of a backend person, but I put together a terrible weather app, and first paint is very slow, even though it starts with placeholder data (or serialized data from a previous run); using an HTML view was much faster because it only makes one toolkit objeft and more capable because css layout lets you wrap text around an image nicely. Maybe there's some trick I'm not aware of to make 'native ui' not terrible on Android... but that experience helped me understand why everything is so slow to start.
However "if you do it the naive/obvious way, it performs this badly" is not a good property of a system and still probably explains why so many things are dog slow to get going.
(I doubt I'd do any better than you did myself, mind, I'm pretty sure I have even less idea what I'm doing on android than you do)
I'd be willing to bet the price of a pint that if either of us flailed around on iOS instead we'd probably end up with much better startup time even hardware-for-hardware because the easiest path for us to flail down is probably much saner than the equivalent on android.
(insert rant about APIs needing to make sure the natural path that a newbie takes is also a path that produces -good- results even if they'll still need to git gud to achieve -excellent- results)
Thing is, not only has Android runtime witness several JIT and GC refactorings since Darwin was created, originally worse than Sony and Nokia's J2ME implementations regardless of Google's marketing otherwise, there are so many factors contributing to Android's perceived slowness from bad coded UIs, sloppy programing, cheapstakes OEMs with low performance chips, and so on.
On the other hand on iOS side, due to lack of GC and OS paging, when memory goes bad, applications just die.
Depends how you define "a ton of time". Good general purpose memory allocation algorithms, like the TLSF algorithm [1], guarantee a O(1) bounded response time suitable for real-time use. To your example however, if someone introduces extra computation into math-heavy hot-looping code, then that is just sloppy development as their adding extra computation. That extra computation being memory allocation is tangential.
[1] https://www.researchgate.net/publication/4080369_TLSF_A_new_...
I described observing programmers I've worked with struggled to understand that memory allocation could *ever* have a significant computation cost.
...then this code didn't get the point of manual memory management, which is to minimize allocations and move them out of the hot path. Unfortunately a lot of C and C++ code is still stuck in a 1990's OOP model where each individual object is explicitly constructed and destroyed, and each construction and destruction is linked to an alloc/free call. If you do this (or reach for reference counting, which isn't much better), a GC is indeed the better choice.
Absolutely not. It just requires a certain amount of planning and puts work on the callers to ensure that they prepare a suitable allocation somewhere, which may be on the stack or inside some structure or array that already exists.
The limit case is the common embedded style of statically allocating everything. Often combined with a ban on recursion and (manually or automatically enforced) limits on stack size. If you don't have a lot of bytes you can plan your usage of each of them individually.
MISRA rule 20.4 just plainly states "Dynamic heap memory allocation shall not be used." The very opposite of GC.
https://wwwfiles.iar.com/superh/guides/EW_MISRAC2004Referenc...
https://tigerbeetle.com/blog/a-database-without-dynamic-memo...
As apposed to the language, compiler or system always making those decisions.
Note that GC cannot possibly promise "time-boxed pauses" in the general case; either allocations are allowed to outpace collections, in which case a longer collection pause will eventually be required to avoid memory exhaustion, or else allocations must be throttled, which just pushes an unbounded pause forward to allocation time.
While Rust made Cyclone's type system more manageable for mainstream computing, everyone else is trying to combine the benefits of linear/affine type systems, with the productivity of automated resource management.
Naturally it would be interesting to see if some of those attempts can equally ping back into Rust's ongoing designs.
* Carp: https://github.com/carp-lang/Carp
* Nim: https://nim-lang.org/
* Zig: https://ziglang.org/
Yes, linear / affine types and uniqueness types can give you a lot of control over resources, while also allowing you to preserve functional semantics.
I would like to see a version of Haskell that doesn't just track IO, but also track totality. Ie unless your function is annotated with a special tag, it has to be guaranteed to return a value in finite time, ie it has to be total. If you tag it with eg 'Partial', you can rely on laziness.
That's very similar to how functions in Haskell can't do any IO, unless they are tagged with 'IO'.
(I know that Haskell doesn't see 'IO' as a tag or annotation. But it behaves like one in the sense I am using here.)
In languages for doing practical calculations, a progress dialog and a cancel button are more useful than a totality guarantee. It should be easier to make complex, long-running calculations safely cancellable.
(Still true with laziness, though it changes a bit. At some point you will ask for a value to be calculated.)
So a default constraint on functions to be total, would be sensible and helpful.
To be able to do the opposite, constrain a function or continuation to never terminate (outside of program termination), would be useful too. Albeit in much fewer contexts.
Any constraint that forces implementations to match respective design intentions is good.
You are technically right, but in practice, finite time does help a lot. To quote from the Dhall documentation at https://docs.dhall-lang.org/discussions/Safety-guarantees.ht...
> Note that a “finite amount of time” can still be very long. For example, there are some short pathological programs that take longer than the heat death of the universe to evaluate. The main benefit of evaluation being finite is not to eliminate long-running programs but to make them significantly less probable. In practice, you will discover that you will rarely author a configuration file that takes a long time to evaluate by accident.
> It should be easier to make complex, long-running calculations safely cancellable.
Just send kill 9 to your program, if you want to cancel it? That seems like an entirely separate topic? (Especially if your calculation is pure, it's always safe to cancel it.)
I don't disagree, but...
Except for excutable sizes and maybe unpredictable performance (performance unpredictability on Haskell has the same shape of UB on C, in that it creeps in, but it's way easier to keep away), there's actually no feature missing.
You can argue for C-like speed (instead of Java-like), but the stuff on the article doesn't have it either.
People have written kernels and unikernels in Haskell. So in that sense it's definitely a systems programming language.
However that comes with performance drawbacks (or at least unpredictable/unreliable performance) which creates the need for languages like Rust. It's great to see the progress in those languages as well.
Well, in the sense that garbage collectors solve memory management. But pure functional programming in the Haskell sense doesn't really manage file handles for you, or database connections.
You could have more predictable performance in Haskell, if you didn't have to deal with mandatory laziness for some functions.
(Basically, in this hypothetical variant of Haskell, by default functions would be safe to be evaluated in any order, strict or lazy or whatever. If you want functions that need to be evaluated lazily, then you'd need to declare that; just like today you already need to declare that your function might have side effects.)
The compiler would then be free to re-order evaluation a lot more, and pick predictable, fast performance.
No, I was actually talking about the latter and not about memory management at all.
In Scala we even achieve this on the library level. (e.g. https://zio.dev/reference/resource/ which also compares the existing problematic try/catch with its own approach)
And despite Scala being strict, the GC still makes it unsuitable for many cases where you just need something like Haskell.
That's what monads are for.
Haskell doesn't require that you use automatic management. But it does absolutely have a solution.
Not a sensible default.
You cannot ask a strict function to behave lazily. But you can ask a lazy function to behave strictly.
Wow. It's like teaching C++ and starting from SFINAE. Or C# and starting from type parameter constraints.
Please think of a real-world examples when teaching stuff. I am very eager to see the program a beginner would need to write that requires: 1) references in a struct; 2) 3 separate lifetime parameters for the same struct.
I think this is a mistake, both on June's part and on Rust's. All low-level languages (by which I mean languages that offer control over all/most memory allocation) inherently suffer from low abstraction, i.e. there are fewer implementations of a particular interface or, conversely, more changes to the implementation require changes to the interface itself or to its client. This is why even though writing a program in many low-level languages can be not much more expensive than writing the program in a high-level language (one where memory management is entirely or largely automatic), costs accrue in maintenance.
This feature of low-level programming isn't inherently good or bad -- it just is, and it's a tradeoff that is implicitly taken when choosing such a language. It seems that both June and Rust try to hide it, each in their own way, Rust by adopting C++'s "zero-cost abstraction approach", which is low abstraction masquerading as high abstraction when it appears as code on the screen, and June by yielding some amount of control. But because the tradeoff of low-level programming is real and inescapable, ultimately (after some years of seeing the maintenance costs) users learn to pick the right tradeoff for their domain.
As such, languages should focus on domains that are most appropriate for the tradeoffs they force, while trying to aim for others usually backfires (as we've seen happen with C++). Given that ultimately virtually all users of a low level language will be those using it in a domain where the low-level tradeoff is appropriate -- i.e. programs in resource-constrained environments or programs requiring full and flexible control over every resource like OS kernels -- trying to hide the tradeoff in the (IMO) unattainable hope of growing the market beyond the appropriate domain, will result in disappointment due to a bad product-market fit.
Sure, it's possible that C++'s vision of broadening the scope of low-level programming was right and it's only the execution that was wrong, but I wouldn't bet on it on both theoretical (low abstraction and its impact on maintenance) and empirical (for decades, no low-level languages have shown signs of taking a significant market share from high-level languages in the applications space) grounds. Trying to erase tradeoffs that appear fundamental -- to have your cake and eat it -- has consistently proven elusive.
High level system languages, that provide a good programming confort, while havig the tools to go under the hood, if so desired.
Being forced to deal with naked pointers and raw memory in every single line of code like C, is an anomaly only made possible due to industry's adoption of UNIX at scale.
The question I'm interested in here is not which features a low-level language should add to make it more attractive for low-level programming, but should it add features that are primarily intended to make more attractive for application programming. The declining share of low-level languages (by my definition) for application programming over the last 30 year, leads me to answer this question in the negative. This is a big difference between the approach taken by low-level languages like C++ and Rust, which try to appeal to application programming, so far unsuccessfully, and low-level languages like Zig, which don't. So far, neither Rust nor Zig have been able to gain a significant market share of low-level programming, let alone application programming, which makes judging the success of their approach hard, but C++ has clearly failed to gain significant ground in the application space despite achieving great success in the low-level space.
The reason I'm focusing on this question is that this article specifically calls out an attempt by the June language to appeal to application programmers, and I claim that C++/Rust's "zero cost abstraction" approach does the same -- it attempts to give the illusion of high abstraction (something that I believe isn't useful for low-level programmers, who make the low-abstraction tradeoff with their eyes open) without actually providing it (clients are still susceptible to internal changes in implementation).
Likewise Rust being adopted by Linux kernel, Microsoft (now the official language for Azure infrastructure, with C and C++ requiring clearance for new projects), Google on Android and Chrome/V8, it is also quite successful for low level coding, alongside the whole GCC/LLVM infrastructure, written in C++.
For example, if I deploy to Vercel or Netfly and don't want to pay for additional infrastructure for webservers, while caring for performance, my options are nodejs addons/serverless in C++/Rust, or eventually Go (which I rather not).
Various features accommodating low-level programming -- those that may have helped C++ take market share away from C but, crucially, have not helped it gain market share in application programming (over the long term) are, therefore, irrelevant to this core question. It's one thing to make a low-level language more attractive to low-level programming, and a whole other thing to make it more attractive to application programming. C++ has succeeded in the former but failed in the latter.
I would say that an higher level language provides more abstractions than a lower level one. Memory and resource management is an aspect of it, but not a requirement (C is an higher level language than asm, yet it doesn't provide any memory management other than implicit stack allocation). In any case yes, the definition is nebulous.
I would add that at the turn of the millennium C++ had a clear domination of the application space.
edit: I don't claim any specific knowledge, but, more than GC, I would say the lack of built-in networking and enterprise[1] features to integrate with web application stacks prevented C++ from taking an hold in the early Internet era (outside of large tech companies).
In the last decade or so, I think the main reason it is being displaced in the desktop space simply by virtue of not being JS.
[1] I'm not using this disparagingly
I personally love C. I think designing a language top-down is a poor approach overall, I prefer the bottom-up approach of the C-inspired for system languages, that aim to fix C rather than this is how the world should beeee!
My own experience coding in this style [1] has been extremely reassuring.
You can generally really safely consider only the context of each process at a time, since there aren't even any function calls between processes, only data sharing.
This meant for example that I could port a PHP application that I had been coding on for years, fighting bugs all over, into a flow-based Go application in two weeks, with a perfectly development time perfectly linear to the number of processes. I just coded each processes in the pipeline one by one, tested them and continued with the next. There were never any surprises as the application grew, as the interactions between the processes are just simple data sharing which can't really cause that much trouble.
This is of course a radically different way of thinking and designing programs, but it really holds some enormous benefits.
https://github.com/rdfio/rdf2smw/blob/master/main.go#L58-L15...
Probably works quite well for systems programming, where things are either "live forever", "reallocate within some pool" (thread handles, file descriptors, etc), or "transient" (for the lifetime of a system call or similar).
Rust's ideal case are domains where allocation management is strictly controlled.
What domain's are those? Do you mean just embedded or perhaps Firefox? Please elucidate.
Everything else is a matter how much one wants to involve themselves into politics of the right way to do memory management, versus get to a compromise for more safer infrastructure.
Right, isn't that what GhostCell and its variants (QCell) are all about? This would be great if it led to a more elegant and principled implementation of that pattern, that could also end up being fully supported in Rust itself.
It may also be nice if constructs that don't cause memory accesses and only ever do the correct thing or crash on the target cpu (such as integer division or pshufb without an address operand on any intel chip ever) were not unsafe. Placing "Well, LLVM says this arithmetic operation is UB and we won't bother to fix it" and "What if one day there's an x64 chip that does something other than crash if it encounters instructions from ISA extensions it does not have?" into the same bucket as "playing with raw pointers" is a bit weird.
It's the first time I hear your second point about intrinsics, for example, and it seems like something that could be done relatively straightforwardly, but introducing "inconsistency" for the benefit of skipping a single unsafe block sounds like the kind of RFC thread I wouldn't want to be a part of.
I accept that languages that are designed collaboratively by huge numbers of people through an RFC process are basically impossible to improve.
Please, no exceptions. No exceptions.
There was a language featured on HN recently that did a good job of making it trivial to build sum types for results/errors from disparate other sum types for results/errors. It can be made easy while retaining the idea of using a sum type for results.
But I think the ISA extension thing is absolutely a good idea for the simple reason that if that ever changed you would be -screwed- and forcing people to Think Really Hard about their usage if ISA extensions is probably a net win anyway.
Possibly they should be in a second "bucket of scary stuff" with a different set of hazard stickers applied, but using unsafe for all of it makes sense from the POV of 'unsafe means I am voiding my warranty inside this block' rather than anything more specific.
1) Prefer the stack wherever possible.
2) RC.
3) Unique pointers by default unless explicitly noted otherwise.
4) Immutable arguments and returns by default unless explicitly noted otherwise.
There's a language that does this all already, and it's called Nim.
let x = new Foo()
if (y == 1) {
recycle x
}
println(x)That would be trivial to do as a runtime check, don't know if the compiler is smart enough to catch such things at compile time.
Also not sure if the idea of a 'copy count' is better than a 'generation counter' which also provides runtime protection against dangling access, e.g. see https://floooh.github.io/2018/06/17/handles-vs-pointers.html
It is the be-all and end-all that will make those scenes in Star Trek where they alter some core starship system programming in 2 minutes flat without mistakes actually plausible.
What's really lacking are safe, easy, strong typed general purpose languages that can leverage AOT compilation for high performance and static analysis etc. A language with the learning curve of Python, near C performance and strong safety guarantees of Rust. There is nothing that suggests to me such a language would not be possible. Swift and C# come closest but they are warped by their respective corporate overlords.
The funny thing is that MACLISP could do this back in the early 70s. While Lisp is a dynamically typed, GCed language, MACLISP let you annotate variables to promise that they would only be called on certain primitive types, thus supporting compile-time optimizations for numeric code and not necessarily allocate memory, follow a pointer, unbox data etc. This was critical to make packages like MACSYMA run on machines with performance in the KIPS range.
Although languages like Python support similar declarations or annotations, they aren't used in the same way -- if you want performance you write the module in C++ and give it a python interface.
And woe betide you if you happened to violate the preconditions of one of those annotations. That kind of programming is no better than C with "Segmentation fault. Core dumped."
The problem is that "system programming" or "embedded programming" isn't one thing.
There are people who want to throw around a zillion polygons at 144FPS. There are people who want max performance on x86-64 shoveling around millions of network connections. There are people who need guaranteed real time response or someone dies. There are people who need to stay asleep all the time to conserve battery and only wake up once every 5 minutes to chirp some RF.
These people do not have the same needs in a language yet they almost all wind up shoveled into C.
Why is that tho? There are better languages for each of those applications. What do you think, is it business requirements? Hardware? Regulation? Legacy code?
Umm, this is MACLISP we're talking about -- you know the types at runtime and can pass the unspecialized argument to an ordinary function. A kind of generic function I suppose, though we didn't use that vocabulary back then.
Just because this was 50 years ago doesn't mean that programmers were morons.
I was recently musing about this on Mastodon[0], commenting on a tweet that said something to the effect of "C++ isn't complex, it just doesn't lie about the complexity of reality". I think Rust is similar, and really any system language has too be. However, there's a space between lying about reality and fully reflecting reality where useful abstractions, such as Rust's lifetimes live. If you hardline the "lying about reality" framing, any abstractions on top of machine code must be ruled out. So while I see where you are coming from, I think lots of space to improve system programming, as Rust did.
> What's really lacking are safe, easy, strong typed general purpose languages that can leverage AOT compilation for high performance and static analysis etc. A language with the learning curve of Python, near C performance and strong safety guarantees of Rust. There is nothing that suggests to me such a language would not be possible. Swift and C# come closest but they are warped by their respective corporate overlords.
I agree about Swift fitting this mold, it's unfortunate that it has failed to gain traction outside of Apple's ecosystem.
C++ also does "lie" about reality in a lot of ways, in the sense that the actual compiled program behaves quite a bit differently than a plain reading of the code implies to a nonexpert. The most obvious form of this is the rules for effect ordering. Even the recurring complaints about the compiler doing unexpected things based on the as-if rule and undefined behavior seem to count here.
"C++ Initialization Story: A Guide Through All Initialization Options and Related C++ Areas"
https://www.amazon.com/Initialization-Story-Through-Options-...
"Undefined behavior" is not reality; it's a strange shadow world where anything may happen. The compiler reserves the right to reject your reality and substitute its own - which it will not show you within the language, nor let you choose or hint, nor warn you.
People like to use C and C++ as if they were a species of typesafe macro assembler that always produces predictable machine code, and that breaks down often enough that the world is full of systems-level CVEs.
Most real world security issues have nothing to do with code. Social engineering breaks more security than memory issues. We are also skewed by many of the fundamental programs are written in C and so there is a lot of value in finding holes.
I'd wonder whether that's just me being dim, but if so then I think Bjarne Stroustrup and Herb Sutter are dim in the same way. (Stroustrup, quoted approvingly by Sutter: "Inside C++, there is a much smaller and cleaner language struggling to get out." and "Say 10% of the size of C++ in definition and similar in front-end compiler size. ... most of the simplification would come from generalization.") And it doesn't seem likely to me that they are ignorantly overpessimistic about the complexity of C++.
To surprise of many outside of .NET community, it has much better performance than Swift[0][1][2] and lets you match performance of C and C++ in areas that matter.
[0] https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
[1] https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
[2] https://benchmarksgame-team.pages.debian.net/benchmarksgame/... (better performance for short-running benchmarks sensitive to JIT)
[bonus] C# AOT vs Go https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
(no direct comparison but Tl;Dr: ARC and Swift defaulting to virtual dispatch that can't always be elided with WMO results in Swift having much lower (even if more consistent) performance)
The question is: is it harder than it needs to be due to accidental complexity[1] in programming language design. TFA argues that there is still some accidental complexity in the design of Rust that leaves room for an "easier" language that still allows the level of control needed for a systems language.
[1] https://medium.com/@sharkaroo/navigating-complexity-in-softw...
And while Android ART technically isn't Java (the plaform), its mixed execution mode with hand written Assembly interpreter, JIT, AOT with PGO shared via play store is quite cool.
Sounds like Go or Zig, though Go is slightly less safe and slower - in turn being much easier.
Though I'd reach for Go first if I'm working with anything concurrent. Concurrency is hard, and Go really helps with getting it right.
Sure, you can compile and host your .NET Core web app on Linux these days, but desktop applications are a completely different beast. You're often lucky if one exists at all, and if it does there's a decent chance it's not designed for "modern" C#-on-Linux. It really isn't a viable option yet, maybe in a decade or two.
Sometimes classes aren’t the abstraction I want to use.
That’s why I like kotlin over Java or c#. It’s be nice to have a language like that which targets .net
Also, JVM ecosystem does not offer the ability to provide zero-cost abstractions, which C# does with monomorphized generics. This is a hard requirement for productive systems programming if you don't want the C level of verbosity.
Any evidence for this? From the benchmark game it seems like c# is more performant than go, and measurements are done on Linux.
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
Lets not forget that C# only exists because Sun won the lawsuit over J++, where several C# features were born (J/Direct => P/Invoke, events, JFC => Windows Forms, COM support), and Ext-VOS (the COM next generation runtime) paper refers to J++, before COOL became C#, and J# was introduced as migration path from J++.
Ironically, after all these years, as means to keep Azure relevant for the Java community, Microsoft has become a OpenJDK contributor by acquiring jClarity, including ARM support on Windows, better escape analysis, and has their own distribution.
And VSCode plugins for Java, developed in collaboration with Red-Hat, are much better than C# Dev Kit, without requiring a Microsoft account.
This allows for a spectrum of JVM implementations, where basically any CPU capable of running some form of Java implementation has a JDK available.
https://en.wikipedia.org/wiki/List_of_Java_virtual_machines
Likewise, most frameworks are driven by set of companies, based on industry standards, where .NET due to its culture, most Microsoft shops tend to only adopt what comes from Microsoft.
It is a long discussion problem in the .NET community that when many FOSS projects finally manage to get enterprise adoption, Microsoft ends up coming with their own solution, which said enterprises then switch to, thus killing those FOSS efforts.
Listen to big podcasts like .NET Rocks, where this tends to be often discussed with their guests.
The first thing that crossed my mind reading this comment was Nim. It’s pretty Pythonesque (but that’s kinda what I hate about it.)
Also channels and WaitGroups are easy to misuse (well, that's why there's also an ErrGroup now).
I'd make Golang my 100% go-to language if it got rid of several footguns.
Though let's be real, that's absolutely certain to never happen, they take their backwards compatibility extremely seriously. So we'll have to keep relying on checkers and linters that alleviate some of the pains somewhat.
- Strip out the bad parts.
- Add types, more functional features, a proper standard lib, and a standardized module system.
- Allow compilation directly to performant machine or byte code.
They can call it a different name if they want.