10 ms·
Bun, JavaScript, and TCO
- sbarre 3y agoTCO in this article = Tail Call Optimization, not Total Cost of Ownership. It makes the article more interesting!
- gerikson 3y agoIt's also not Tjänstemännens Centralorganisation, the largest white collar union in Sweden, and also the org behind the TCO labelling of computer monitors.
- sbarre 3y agoIf you google TCO, at least where I am (North America), "Total Cost of Ownership" is the first result - and the dominant one on the first page of results. It's also the main definition of TCO that most people are probably familiar with, me included. This felt like a reasonable clarification to make.
- davidy123 3y agoI guess for anyone interested in Bun and Javascript, it would be more obvious. User what does "TCO" mean in " Bun, JavaScript, and TCO" ChatGPT "TCO" in "Bun, JavaScript, and TCO" refers to "Tail Call Optimization."
- zelphirkalt 3y agoUsually not for JS people, because they don't get to use recursion much, due to decisions by browser makers. More likely that people from other, usually FP languages think of the actual meaning it has in the article or in the computer programming world.
- smarx007 3y agoActually, as a chiefly Java/C# person, I was hoping for the article to cover how Bun helps lower the Total Cost of Ownership of Javascript projects by helping to get off the hamster wheel of infinitely deep npm dependency trees, wild west of constant project deprecations and major version releases with immediate deprecation of previous versions, daily game of CVE alert whack-a-mole etc. Preferably, short of writing all the code yourself.
- sbarre 3y agoI also assumed the other TCO when I clicked through, which would have been an interesting take to read for sure (particularly since Bun is so new, so I was wondering how much data would be backing this analysis), but I'm not a strong functional programmer so any time someone covers functional-adjacent topics, it's interesting to me! I'm with you on wanting to learn and explore more about Bun's main advantages though, the bundled tooling and some of the convenience APIs feel like well-planned time/effort/maintenance optimizations.
- deleted 3y ago[deleted]
- midtake 3y ago> [The tail call optimized] function is starting to look a lot like the orignal for loop solution. It’s not very succinct or elegant anymore. (Brackets mine.) I don't know about succinct but I definitely like how it looks a lot more. It's very readable, while the ternary operator one looks illegible at that length. It looks shoehorned in. It's the programming language equivalent of trying to mumble a whole sentence in two syllables.
- k__ 3y agoYes, every language should have if-expressions. Don't know what they were thinking with the ternary operator.
- JonChesterfield 3y agoOne reason I've heard for the statement vs expression distinction, where one deliberately makes a mess of the syntax uniformity, is that it helps diagnostics of programming errors. That is, by demanding spurious restrictions on syntax and generally making code more annoying to write, you get to detect more constructs as probably bad. Line noise - semicolons in C, colons in python - is the same idea. Earlier diagnostics of code that probably wasn't intended. I don't find this remotely compelling as a language design choice but it's the best justification I've come across for why so many have the extra obfuscation between programmer and AST. Specifically, why would one optimise for ease of reading invalid code instead of for ease of reading valid code. Madness. But popular.
- recursive 3y agoHow are if-expressions different from the conditional operator? I thought one was a concrete implementation of the other.
- djur 3y ago"if" comes before the condition, "?" comes after. For a lot of people this seems to significantly improve readability.
- 3y ago
- imjonse 3y agoIt's nice, but the downside is that relying on TCO can make your Bun-tested code unexpectedly break with stack overflow error if it ever gets run on Deno or Node. So probably a good idea to comment this part of the code and make sure if it's in a library to similarly warn the callers somehow.
- bryancoxwell 3y agoDoes serverside JS have anything similar to #ifdef?
- antipurist 3y agoSomething like if ('Bun' in globalThis) ... if ('Deno' in globalThis) ... if ('window' in globalThis) ... could be used to determine the runtime.
- timw4mail 3y agoThat certainly works for Bun and Deno, not sure about what is effective in Node, though.
- basil-rash 3y agoChecking for process.versions.{node,bun} works, not sure if Deno has an equivalent.
- deleted 3y ago[deleted]
- vlovich123 3y agoYes. You can define a constant (eg IS_SERVER) which your bundler (eg esbuild) replaces with a specific value depending on what environment you’re targeting. There are also ways to detect it using runtime globals that are only defined within the browser although that can be monkeypatched by your own code or 3p libraries you import (not common but could be a compat layer you add to make server side JS behave more like a browser).
- pcl 3y ago> Recursion takes up precious memory on the call stack! There may be commands to increase the call stack size for your program, but there is only so much the OS will allow. Memory on the heap is much less restricted. This reasoning implies that tail call optimization is some sort of memory-segmentation workaround. This isn't accurate. A (non-TCO) recursive approach is more expensive because it uses O(n) bookkeeping memory, whereas the iterative approach uses O(1) memory. Naive recursion will allocate a stack frame for each "iteration", whereas the loop approach will not allocate anything per iteration. So, the iterative approach simply uses much less memory for large iteration counts; the placement of the memory in stack space or heap space isn't the relevant factor.
- fyrn_ 3y agoBut without TCO, even if your function doesn't have any state of it's own, it will use memory on the call stack. I don't think anything about what they said implied memory segmentation was the problem. It's pretty clear they mean each recusion increases the size of the call stack without TCO.
- rezonant 3y agoAgreed, I think the mention of heap space was more to answer the question of someone new to this topic of "but wait, I can allocate gigabytes of data in an array, why can't I allocate 100,000 stack frames?"
- brabel 3y agoThe performance difference is not just about TCO, but about creating a new array on each iteration instead of reusing the old one... in Lisp, because it uses cons cells which share structure, appending is very efficient, so the recursive code runs as fast as it can get... not so much with JS arrays.
- pjmlp 3y agoEven in Lisp, if performance matters there are other data structures. We are decades away when lists were the only option.
- brabel 3y agoIn the example in this blog post, I am quite certain plain LISP lists would still be the right choice today.
- odyssey7 3y agoECMAScript continues to evolve and I suspect that there would have been an effort to make the spread operator into a sort of cons in JavaScript. It could have worked for both arrays and objects. However, after seeing that the entry-level bar of proper tail calls couldn’t make it out the door for Chrome and V8, they might have decided not to push it and risk further divergence from a major implementation.
- ColonelPhantom 3y agoIsn't prepending the efficient operation? Appending would require mutation or copying, prepending only requires a single new cons cell. Appending to a linked list is fine if you can mutate and keep a pointer to the tail, but then again, extending mutable arrays is also amortized O(1) assuming a reasonable allocation scheme.
- brabel 3y agoThe common pattern in LISP is to prepend using cons and then reverse the list at the end if order matters. Check this program as an example: http://www.norvig.com/java-lisp.html http://www.norvig.com/java-lisp.html Recursion is done with `(cons (nth-digit digits start) words)` and recursion ends with `(format t "~a:~{ ~a~}~%" num (reverse words))`.
- JonChesterfield 3y agoTCO should be table stakes. An interpreter can do it by noticing that the next thing is a call to itself (the interpreter), a compiler by reorganising the stack frame before the jump. Lots of stuff gets in the way. Destructors, varying type signatures, calling conventions. But for the case where it can happen, it should be considered an implementation error that it does not. Very like a space leak. edit: this ^ was evidently unclear - tail call support in an interpreter means recognising when the interpreter is about to call the interpreter and jumping there, e.g. in an eval-apply setup, you use one frame for the eval-apply-eval-apply skeleton and only spawn more for evaluation of function arguments. Tail call support in an compiler involves changing the calling convention to clean up before jump. At that point it's all jumps, whether back to the top of a loop or to some other basic block, because all the world is SSA to a pretty good approximation. Neither of those makes any meaningful distinction between calls-to-self, calls-to-sibling, calls-to-indirect and so forth. The TCO is easier on self calls idea comes from languages where it is hacked before the compiler backend in a setting where goto isn't allowed to cross function boundaries. Some C code will have a label at the top named "self" or similar and use `goto self;` to force the equivalent of a tail call, some compiler stacks implement TCO by a mechanical version of the same hack and thus can't deal with it crossing between different functions. edit2: If you're compiling to a target with restrictions on calling convention that preclude cleanup before jump (and doesn't sort this out itself) you are out of luck. Pick a better target or live in the doomed world you've created. See e.g. https://v8.dev/blog/wasm-tail-call https://v8.dev/blog/wasm-tail-call for some stuff on wasm trying to fix itself, I haven't kept up to date with whether they did or not.
- anonymoushn 3y agoTCO is broader than tail calls to the same function, but tail calls to the same function would certainly be a start.
- vitus 3y agoTCO is about more than self-recursive calls -- you should be able to handle mutual recursion: f = x => x > 0 ? g(x - 1) : 0; g = x => x > 0 ? f(x - 1) : 0; (These functions don't do anything other than stress-test the stack, then return 0.) Note that if I changed this to, say, 1 + g(x - 1), this would no longer fall under the purview of tail recursion, where the last instruction before the return is a recursive call. The usual workaround I learned in my SICP days was to add a second variable for accumulating any results. And, indeed, that's how the blog post rewrites the recursive function. (The recursive one-liner is still wildly inefficient because JS doesn't implement arrays as linked lists, so the spread operator results in a copy for each recursive call, resulting in a quadratic solution. It could be made more efficient by using Array.prototype.push, but then it's no longer a pure function.)
- leeoniya 3y agothe reason TCO is not implemented in V8, iirc, is because of developer experience and needing devtools to faithfully dump the call stack that hasnt been flattened, because that's what's expected of js DX. does JSC's implementation solve this? do they exhaust the stack only when devtools are open, or smth? maybe they just keep the last 10 frames in memory for devtools? (that would make most sense to me)
- pjmlp 3y agoThis is a solved problem on programming languages where it is part of the specification, like Scheme. Basically the debugging info and what actually happens isn't 1:1, rather the logical model of the execution.
- anonymoushn 3y agoThis is a silly justification I think, in the sense that V8 could implement this in a way that can provide stack traces for all stacks that are short enough for a human to browse while also executing programs that use tail calls as goto correctly.
- hajile 3y agoNobody cares that loops don’t have stack frames. Few people cared for decades that async functions lost stack traces. It’s just a bad excuse.
- leeoniya 3y ago
- MrJohz 3y agoI think this article actually does a really good job of explaining why TCO hasn't really been an important part of the JS ecosystem. There's a lot of situations where recursive algorithms are really neat and clear. I don't know if this is the best example, but it shows the benefit of being able to split logic into a base case and a recurrence case. But, in my experience, an algorithm that elegantly fits a recursive relationship is rarely one that naturally fits the tail-call paradigm. Often part of the benefit of recursion is that you can store state in the stack - the very thing you need to avoid to use TCO. This means you often need to put in effort to create a tail recursive algorithm. But that often ends up looking a lot like the imperative case anyway - an accumulator outside the loop that you either mutate manually, or update in a tail call. And in my experience, the mutating, imperative version is usually then the easier to read and write (assuming you can keep mutations to a given scope, and not have that state leak all over the place). (In fairness, this might be more familiarity, though.) In the light of this, what is the advantage of TCO? In functional languages without mutation, it's pretty important to allow for functions to act on arbitrarily-sized inputs without constantly growing the stack. But if we have mutation, it's really just a different way of writing the same code. And if that different way is generally less clear and almost always less performant, it probably isn't a very useful choice. Which is why I think TCO hasn't really caught on in the other JS engines. It's a cool idea, and there's definitely a handful of cases where it's the useful way to go, but usually you'll be better served by writing things in the more traditional JS way.
- pjmlp 3y agoRegardless, it has been approved as part of JavaScript specification and Chrome folks refuse for political reasons to implement it, which given the market domination everyone has helped them achieve is a bummer.
- deleted 3y ago[deleted]
- MrJohz 3y agoFirefox have also chosen not to implement it, right? Indeed, my impression was that Firefox were far more against the whole thing than Chrome, who did implement TCO but then removed it for various reasons. My impression is that this is less an issue with any particular implementor, and more with the feature not being fully thought through at the beginning. A lot of the browsers (including the Edge team at the time) ended up running into issues, on top of the UX/explanatory problems. That's why there was the alternative proposal for explicit tail calls, but those didn't go anywhere.
- quickthrower2 3y agoIs it just me but I never use recursion in JS (or imperative languages generally) and it never really comes up as a need?
- jiehong 3y agoWe’re using recursion at $company to validate user inputs because it’s a user-defined tree of unknown depth.
- anonymoushn 3y agoFor example if you write a json deserializer that's generic over the struct you want to deserialize to (or one in JS that returns a JS object), you'll usually use some sort of recursion. My generic radix sort[0] also has recursion in it, which seems like the most straightforward way to write it, but of course any recursive function could be mechanically converted to one that does not use recursion. [0]: https://github.com/alichraghi/zort/blob/main/src/radix.zig#L140 https://github.com/alichraghi/zort/blob/main/src/radix.zig#L...
- odyssey7 3y agoNitpick: JS is multi-paradigm.
- quickthrower2 3y agoYeah I should have been more specific. I mean languages where recursion is idiomatic for many problems because the language is purely functional like Haskell.
- kosolam 3y agoThis isn’t a good thing if your fancy recursion code works great on bun but is slow in other js runtimes.
- anonymoushn 3y agoSeems fine if you actually run it on bun.
- imjonse 3y agoRelated: Guido van Rossum's argument for why there is no TCO in Python. https://neopythonic.blogspot.com/2009/04/final-words-on-tail-calls.html https://neopythonic.blogspot.com/2009/04/final-words-on-tail...
- Jarred 3y ago(I work on Bun) A neat thing about tail calls in JavaScriptCore: there’s an explicit bytecode intrinsic for it. return @tailCallForwardArguments(MyConstructor, this); To use this in Bun, you’d have to start Bun with the environment variable “BUN_JSC_useDollarVM=1” and then $vm.createBuiltin(mySourceCodeString) When using this intrinsic, if any of the arguments are incorrect or it cannot otherwise enable it, the entire process will probably crash. In debug builds of JSC it will have a nicer assertion failure but that is not enabled in release builds Example code: https://github.com/WebKit/WebKit/blob/17351231b4dedb62d8172112eaa0661e7b33260b/JSTests/stress/tailCallForwardArguments.js#L16 https://github.com/WebKit/WebKit/blob/17351231b4dedb62d81721... also happy to answer any questions about Bun
- CodeGroyper 3y agoLove bun, thank you so much Mr. Sumner. What is the priority of app router integration for NextJS?
- johnfn 3y ago> What is the priority of app router integration for NextJS? I'm not Jarred, but what do you mean by this? I'm using bun + app router + NextJS and everything seems to work just fine.
- atmin 3y agoNot OP, but interested: can you deploy on a vps having only bun and not node?
- maxboone 3y agoYes
- reducesuffering 3y agoI don't think you're talking about what GP comment is. For clarification, Bun can act as a package manager like npm (probably the case of "bun + app router + NextJS" comment), and it can act as a replacement to a node runtime a la Express on a VPS (I'm assuming this is what you mean by "yes"). But Bun currently does not implement enough of the Node API's to use Bun as the runtime for a Next.js app. From Bun themselves: "The Next.js App Router currently relies on Node.js APIs that Bun does not yet implement. The guide below uses Bun to initialize a project and install dependencies, but it uses Node.js to run the dev server." https://bun.sh/guides/ecosystem/nextjs https://bun.sh/guides/ecosystem/nextjs
- magic_man 3y agoYou can use a loop and a stack and can get recursion without adding all the overhead of a function call.
- refulgentis 3y agoI spent the first year or two of my career thinking I needed to Do Recursion because thats what the textbooks said and hey, the language supports tail calls! I learned, in the sense you learn by touching a hot stove, that: A) you can't guarantee the compiler sees it as a tail call and optimizes it. B) you are now open to a stack overflow appearing in your software at any given point due to compiler changes / your own changes that confuse the compiler, etc. C) qed, don't do tail calls.
- kriiuuu 3y agoBoth Scala3 and Kotlin allow you to annotate functions with @tailrec which will give you a compiler warning if the compiler can’t optimize. And if you use the xfatal-warn compiler flag the Scala code won’t compile if your function is not tail call.
- FpUser 3y ago>"I spent the first year or two of my career thinking I needed to Do Recursion because thats what the textbooks said" Being an old fart I've learned long ago to not follow self declared prophets. Recursion is a trade off that comes with the cost. Sometimes it makes sense to use it and sometimes (most of the times) it does not. You do what makes you and your customers happy.
- timw4mail 3y agoIterating over tree structures is a pain without recursion, but that's the only situation where I feel I need recursion.
- ivancho 3y agoI don't think you can use tail call recursion for tree walking unless you also manually maintain another stack. And at that point iterative code looks just as readable
- chrismorgan 3y agoThis is not actually about Tail Call Optimisation, which is more flexible and optional matter of optimisation, but about Proper Tail Calls, which are a guarantee made in the ECMAScript 6 specification (over implementer concerns objections)—in strict mode, calls in tail position must not create additional stack frames. This is the last piece of ECMAScript 6 that most engines haven’t implemented, because it’s rather controversial: it actually causes some performance problems, and makes debugging harder, and may have security issues (in 2016, Mozilla declared it impossible to implement across realm boundaries due to their security model). https://github.com/tc39/proposal-ptc-syntax https://github.com/tc39/proposal-ptc-syntax has a lot of useful information about it all, and a proposal to make it explicit in syntax, such as with `return continue …`, though I don’t believe that’s really gone anywhere. The practical situation is that this is the one part of the ECMAScript spec that most implementers ignore, and thus which you can’t depend on. Which says to me that it should either be made optional or be removed from the spec. Not sure if there are any other features similarly disregarded. ECMAScript specification policy was different in those days, they operated more independently of implementers. (HTML was like that once too—that’s roughly why WHATWG was formed, because the actual implementers weren’t happy with how things worked in W3C, so they took matters into their own hands.) (Fun terminology problems here. The term TCO is commonly used for PTC, and PTC is very close to being a subset of TCO, but the mandatory stack frame elision which ruins debugging feels to me like it falls outside of TCO. In various situations, debuggers will mark things like “stack frame omitted” when they’ve optimised one out of existence, but you can generally compile things differently, or something like that, to prevent this. (Compiled/dynamic language variation showing up here.) But with PTC, it feels like the engine is kinda not even allowed to know that a stack frames may be absent. So I say PTC and TCO are a little distinct, though PTC is mostly just a subset of TCO. Reminds me of the terminology of tree-shaking versus dead code removal—where the former is essentially a subset of the latter, but that the effects are just slightly different, though I’d say it’s more slight in that case than this.)
- 65 3y agoSo the optimization here is that instead of creating a new array every time you call the count function recursively, you're only modifying a single array. Thus the new array recursive function is significantly slower because we're storing all those arrays in memory when calling the count function recursively. Do I have that right?
- snissn 3y agoI gave bun a test with react apps and found that it installs node_modules much much faster, but starting up a react dev server took the same time
- jart 3y agoTCO is cool. I remember how enlightening it felt when I studied Scheme and came to understand how it's implemented there.
- deredede 3y agoIf this is not what you're referring to, you might be interested in CHICKEN Scheme's implementation, which is unlike any other I've seen: instead of compiling tail calls to jumps, they are just regular calls, and the call stack is effectively garbage collected when it would overflow.
- jtlasdfjwfasdf 3y agoAgreed. Scheme taught me that function invocations didn't have to be sullied with the risk of stackoverflow, and in-fact what appeared to be recursive was actually iteration and loop constructs were not needed.
- mwkaufma 3y agoOptimization and functional recursion is nice and all, but the unsung killer-feature of (mandatory) TCO is to (ab)use the stack as a state-machine. Each "state" is a function which tail-calls the next state, so it replaces the stack frame. Stack-traces now double as state-inspectors. Substates naturally follow from subroutines. I regularly use this in Lua gameplay scripting, which has proper tail-calls in the language spec, not just as an implementation-optional detail.
- koito17 3y ago> Languages that rely on recursion like LISPs often specify that TCO must be implemented in their language spec. This is inaccurate. As far as I can tell, it's only Scheme specifications like r5rs that have a hard requirement on tail-call optimization. The Common Lisp specification makes no mention of tail-call optimization, and Clojure -- arguably the most widely used Lisp today -- does not have it either (but it has special forms and macros that let you write recursive code and produce trampolines, thunks, etc. to avoid blowing up the stack). With that said, at least in the case of Common Lisp, it is true that many compilers will implement TCO, even though it is *not* required at all to conform to the specification.
- lispm 3y agoCommon Lisp is not a Lisp which 'relies on' recursion. It has various loop statements (DO, DOTIMES, DOLIST, ...), various mapping functions (map, mapcar, mapc, maphash, ...) and a complex LOOP. To prevent stack overflows those can all be built on top of a goto operator (tagbody + go). One of the reason was that compilation targets (cpus, virtual machines, other languages, ...) don't have native TCO support. For example the various Lisp Machines had no TCO support, and many C compilers did not support TCO for quite some time. C is a popular compilation target (KCL, AKCL, ECL, CLASP, CLICC, ... were (some are) all Lisp to C compilers). > With that said, at least in the case of Common Lisp, it is true that many compilers will implement TCO, even though it is not required at all to conform to the specification. The specification does not require it, it actually says nothing about it. TCO isn't even mentioned. Means, it also says nothing how a compiler should support it, if it wanted to. The language supports recursion, but something like tail recursion support is entirely an implementation specific optimization. Since TCO has some advantages (less stack space needed, possibly some faster loops, ...), many compilers implement it, but mostly no interpreter does it. Also, most of them support GC, even though exactly nothing is said about it in the specification. ;-)
- reactordev 3y agoNot to be a dog in the fight but… How is: const count = (amount: number) => (amount > 0 ? [...count(amount - 1), amount] : []); Succinct and better? It’s fewer lines. It uses recursion. But it’s obtuse and illegible syntax diarrhea that takes more time to grok. The for loop example above, while simple, is easily understood. A junior engineer could fix it. Is it faster? No. Is it easier to understand? Yes. I like the final example as well. Look, I’m all for being clever when cleverness is needed but some of you JS/TS folks take it to the extreme. I want to be able to read my codebase, not perform archaeological studies. I have the same issue with Rust syntax as well in places. I will praise the article on this though, optimizations do matter and having something execute orders faster will improve your overall experience. It doesn’t have to be cuneiform. If you must be clever, wrap it in an abstraction that is well documented because you don’t live forever and neither will your code, make it easy(ier) on the next person. While you can nest a recursive function in a tertiary statement coro, don’t. Fire is cool but also burns. Btw, bun is blazingly fast. I look forward to more.
- mhink 3y ago> Look, I’m all for being clever when cleverness is needed but some of you JS/TS folks take it to the extreme. To be fair, this is very much a toy example meant to demonstrate tail recursion- although I do agree it's not a great example considering you need to understand the evaluation order of ternaries in order to understand why one version is tail-recursive and the other isn't. That being said: generally speaking, one might argue that using recursion at all is "too clever" and algorithms should just stick to iteration altogether. ¯\_(ツ)_/¯ > While you can nest a recursive function in a tertiary statement coro, don’t. Man, why do you gotta call me out like this? :D
- akoboldfrying 3y ago>algorithms should just stick to iteration altogether Well, if your algorithm performs 2 or more recursive calls per function invocation (like, say, quicksort), at least one of them needs to be an actual recursive call that uses additional stack space, since TCO is only able to mitigate a single recursive call per function invocation. (You could simulate your own stack and use iteration... but the only reason to do so in practice would be to escape some artificial restriction on native stack size.)
- cj 3y agoBased on the title, I was hoping for a TCO (Total Cost of Ownership) analysis on Bun/Javascript. Or the cost of running a company’s architecture on a “new” (not really new, but quickly evolving re: frameworks) JavaScript.
- qudat 3y agoWhile working on effection@v3 (https://github.com/thefrontside/effection https://github.com/thefrontside/effection) we spent a bunch of time ensuring that our delimited continuations could handle deep recursive call stacks in Deno. PR: https://github.com/thefrontside/continuation/pull/11 https://github.com/thefrontside/continuation/pull/11 TCO would have definitely simplified this issue. What’s worse is hitting maximum memory callstack exception is very tricky to catch and is not reliable across runtimes. So when a user hits it it can be tricky to track down.