10 ms·
John Carmack on Inlined Code (2014)
- dmitshur 6y agoIs the pattern of putting the publish year when it’s not the current year still used on HN? If so, I think this needs a (2007) or (2014) suffix.
- jspash 6y agoOut of curiosity since I haven't touched C/C++ since university, but has much changed since 2014? Or even 2007 in the world of C that a date is needed? I (naively) thought that C was pretty much "done". And any articles written recently were just for gilding the lily.
- mhh__ 6y agoC++ hasn't meaningfully changed a huge amount since '14, although the committee's latest abominations are starting to hit the big time. C didn't have proper atomics or a memory model until 2011 if I'm not mistaken, and that is important.
- ratww 6y agoI'm going to disagree with sibling and say that a lot has changed since 2007. The biggest game changers arrived in C++11 like auto and move semantics, but C++17 also introduced some interesting stuff like optionals, destructuring, folding expressions and lambda capturing this by value. Here's a list with code samples: https://github.com/AnthonyCalandra/modern-cpp-features https://github.com/AnthonyCalandra/modern-cpp-features As much as I enjoy hating on C++, I have to admit most of the new features are great.
- tda 6y agoNice food for thought. For those like me that read the comments first: "To sum up: If a function is only called from a single place, consider inlining it. If a function is called from multiple places, see if it is possible to arrange for the work to be done in a single place, perhaps with flags, and inline that. If there are multiple versions of a function, consider making a single function with more, possibly defaulted, parameters. If the work is close to purely functional, with few references to global state, try to make it completely functional. Try to use const on both parameters and functions when the function really must be used in multiple places. Minimize control flow complexity and "area under ifs", favoring consistent execution paths and times over "optimally" avoiding unnecessary work. Discussion? John Carmack"
- quelsolaar 6y agoI have always liked much longer functions then the average programmer. The main reason is that we read sequentially. It much easier to follow something sequential, then something jumping around. A lot of bugs happen when you see a function call that you think you know what it does but doesn't. There is a reason regular front-to-back books are more popular then choose-your-own-adventure books. You know where you are, and you dont spend all day flipping back and forth. I also find that when you start splitting up your functions down to 5 lines, it becomes almost impossible to differentiate what the different functions do clearly, and that makes good naming almost impossible. EDIT: Also, I dont understand why people complain about functions being longer then 5 lines making code hard to navigate, and then turn around and write header only files with 10000 lines of code....
- hvidgaard 6y ago> There is a reason regular front-to-back books are more popular then choose-your-own-adventure books. You know where you are, and you dont spend all day flipping back and forth. I don't think that has anything to do with it. It's a roleplaying adventure where you need to keep track of things on a piece of paper and use dies for encounters. People that want to read don't want to participate, just consume. Active vs passive. Regardsless, splitting 4-5 lines of code out into a function and giving that a proper name can enhance readability significantly. And modern IDE tools make it simple to read that without disrupting the flow. Visual Studio and IDEA for instance has a peak definition that makes it trivial. If that function does not do what it say, that is a different problem.
- srtjstjsj 6y agoInstead of cramming the description into a NonPunctuatedFunctionName, just lay down some scoping brackets and write a comment. IDEs are food at folding code. If the function doesn't need to be called many times, it doesn't need to exist.
- hvidgaard 6y agoCode folding is not good for readability, and creates a significant overhead when reading the code. Even to the point where some static analysis tools default to highlight the use of "regions" as problematic.
- deckarep 6y agoTIL: John Carmack almost shipped a game with 1 extra frame of latency unnecessarily...
- weare138 6y agoMeanwhile at EA...
- snidane 6y agoI have always wondered why functions have to be declared inline when it is more up to the caller to declare whether to inline the contents of the function at call site. So instead of inline int f(int x) { return x * x; } int main() { f(3); } you'd want to do int f(int x) { return x * x; } int main() { inline f(3); } I have seen this implemented in Zig for loops (inline for, inline while). Is there support for this in other languages?
- patrec 6y agoYes, Common Lisp does this right, see: http://clhs.lisp.se/Body/d_inline.htm http://clhs.lisp.se/Body/d_inline.htm
- thelopa 6y agoSort of. I think CL has the right direction but the details are wrong. This pattern requires declaring the function notinline, and that is a much stronger statement than just “wait I take it back”. Using this pattern, the function can ONLY be inlined in the contexts where you allow it. Similarly, compiler macros are disabled for notinline functions. I would like the compiler to use its normal judgement for inlining and continue using compiler macros for call sites where I don’t provide an inline declaration.
- patrec 6y agoI think you overlook that inlining in common lisp is a lot less trivial than in very static languages like C++, because it is perfectly valid to redefine functions at runtime. This does obviously not play well with the compiler randomly inlining things behind your back. You can fix that by keeping track of where you inlined f and then re-compile all the inlined sites as well, but that obviously has significant pathologies as well. Having said that, performance oriented common lisp compilers like sbcl (and its predecessor) will generally allow you to block-compile stuff which will get rid of the extra indirections at the cost of less runtime flexibility. IIRC that will also mean the compiler will use its judgement whether to inline a function.
- shureluck 6y agoDid not know this existed, but I thoroughly loved it and agree with his findings. Thanks for sharing.
- warpech 6y agoI love the findings, however, I think that the conclusions made for games might be exactly opposite to the coding style used for business software.
- 29athrowaway 6y agoThe compiler can inline things for you. There is a way to specify that a function should be inlined: inline. https://en.cppreference.com/w/cpp/language/inline https://en.cppreference.com/w/cpp/language/inline If this specifier is used, then when your inlined function is compiled there will be no function call, just the inlined code. This is just a hint for the compiler, though. The compiler can ignore this hint, and usually does.
- gpderetta 6y ago"In no way, shape, or form am I making a case that avoiding function calls alone directly helps performance."
- arcturus17 6y agoI don't think I understand the relationship between inlined functions and functional programming established in the article. As I see it, whether you inline or split into functions or subroutines, you can have functions be pure, in the sense that they don't mutate state. In my experience with functional programming, splitting code into smaller functions is not a problem but rather encouraged too, for the sake of readability (so no different than other paradigms). There must be something that escapes me, possibly at the systems level. Can someone please explain?
- srtjstjsj 6y agoCarmack agrees with you. He wrote that functional functions are the ideal, but often not possible, and non-functional functions are bad and should be inlined. This is the "functional core, imperative shell" pattern where you have as many small neat functional functions as possible, and one big nasty non-functional main loop for only your mutating state, where every line must be studied carefully in relation to all other lines.
- ZephyrBlu 6y agoThe "functional core, imperative shell" pattern is how I naturally gravitate to writing code. It helps so much with readability and understanding what the code does. Trying to read other peoples code that jumps around between many functions with side effects, often being nested 3-4 levels deep, hurts my soul.
- cjfd 6y agoI guess it makes some sense in a tight game loop. I really don't think most non-game programmers should adopt this style. I have actually seen code where lots of stuff was inlined. This resulted in functions that are many-thousands of lines where nesting was so deep that at a particular point you would have no idea inside what 6 levels of control structures you were.....
- latch 6y agoI've read this before and I agree with it. As an elixir programmer, it frustrates me to be reminded of this article because it reminds me of the only thing I find torturous about programming in elixir. Without a way to exit a function early, you either end up with deep nesting (which becomes hard to read/follow after 2-3 levels), or a lot of small function calls to continue/break. In many cases, you can use a `with <-` but if the statement only returns a variable, you need to wrap it into a function (are have a hard-to-read guard clause, which will only work in some cases) to support matching: Say `User.load` is out of your control and it returns nil | user. I'd love to do: user = User.load(id) if user == nil do return :not_found end But I have to either introduce nesting, or decrease the readability with either a guard or a function. Guard: # if we just let `nil` flow through to the `else` we won't be able to tell this `nil` from another with user when user != :not_found <- User.load(id) || :not_found Function: with {:ok, user} <- get_user(id) ... defp get_user(id) do case User.load(id) do nil -> :not_found user -> {:ok, user} end end
- gleenn 6y agoExcellent article. Haven't read something so opinionated but clear and well argued about programming in a while. His summary rules at the bottom are great: To sum up: If a function is only called from a single place, consider inlining it. If a function is called from multiple places, see if it is possible to arrange for the work to be done in a single place, perhaps with flags, and inline that. If there are multiple versions of a function, consider making a single function with more, possibly defaulted, parameters. If the work is close to purely functional, with few references to global state, try to make it completely functional. Try to use const on both parameters and functions when the function really must be used in multiple places. Minimize control flow complexity and "area under ifs", favoring consistent execution paths and times over "optimally" avoiding unnecessary work.
- fxtentacle 6y agoOh, how often I wish that someone would have followed this advice. Working mostly on Java these days, Carmack's focus on efficiently doing the right thing sounds like fairy-tales of the promised land ;) Just yesterday, I spent much longer than I believe is reasonable to fix a bug in a Java class whose sole purpose is to do an HTTP(S) call and determine if the URL is online (200 code) or declared offline (40x code). The first thing that really slowed me down was that instead of having a clear location for the crash, a Java .war inside tomcat tends to vomit 40-50 lines of stack trace onto the console. The reported Exception was "java.io.IOException: Server returned HTTP response code: 400 for URL: ..." in HttpURLConnection.getResponseCode(). But debugging the issue, I noticed that getResponseCode exits just fine without any exception. A bit of Googling around revealed that the root cause was this: https://stackoverflow.com/a/54837353/525608 https://stackoverflow.com/a/54837353/525608 Inside getResponseCode(), an exception is thrown, caught, and suppressed. And then later, it is retrieved out of HttpURLConnection.rememberedException and thrown around by a different HttpURLConnection function. But of course the Exception still had the old = wrong stack trace in it. So those 40+ lines of stack trace that Java garbled up? Completely useless. I kid you not, Java source code with Exceptions is like your own private hell, especially because the control flow tends to be somewhere between "nested inside 30 functions" and "completely random". The latter usually happens when libraries do bytecode patching so that what is actually executed doesn't even match the source code anymore, and that's also the point where stack traces become almost completely useless. I'd take a 2000+ lines monolithic function every day over this unholy mess that ["Enterprise Java" == stacking random libraries on top of each other] has become.
- scaladev 6y agoJust out of curiosity, are there any Java web frameworks with reasonable stack depths? After working on .NET Core codebases for several years (which rarely have more than 4-5 calls within the framework itself) I was shocked to see stack dumps from a Spring application I've been working on. Three to four nested exceptions, with up to 100 nested calls (and sometimes more) within each one. If you don't have a smart IDE folding the less interesting parts (and copious amounts of amphetamine), it's simply unreadable.
- 6y ago
- rossmohax 6y agoThis quote from him is very telling how good engineer he is: > That was a cold-sweat moment for me . after all of my harping about latency and responsiveness, I almost shipped a title with a completely unnecessary frame of latency.
- himinlomax 6y agoWhat about unit testing?
- mattpojk 6y agoI read this article a few years ago when I was in a "CARMACK IS AN ALL KNOWING GOD" phase. So I started using these concepts at work, for business stuff. It ended up becoming an absolute unreadable, illogical mess that only I could possibly understand. Proceed with caution and don't blindly assume that this is the best approach for all situations like I did just because Carmack did it in the Quake engine.
- kzrdude 6y agoMaybe I'm oversimplifying here, but game engines are like marble statues. You start with the block of marble, you sculpt it and at some point it is finished. Ongoing maintenance issues are not really top priority, the game is not going to be a living software project for that long.
- westwing 6y agoGame engines are usually maintained for years if not decades, as they are often enormous investments. However, it's more common to fork (or at least freeze) for a specific project, so in that sense there is more room for ad-hoc solutions.
- rdgthree 6y agoThis is an argument that I've found myself making fairly regularly, and often frustratingly after attempting to hunt down a bug through 10 levels of abstraction that didn't need to be there. Add "debugging complexity" when it's warranted, but don't add it by default. More files and functions mean more jumping around and more potential blind spots. That being said, John Carmack makes the very important point that this decision (whether to inline or not) should be made case-by-case. Someone in these comments used the flow of a novel as an example and I think it's actually the ideal way to describe the balance you want to strike with code as well. Using "The Tortoise and the Hare" as an example: Inlined too much: "The race began. The Tortoise took a step. The Hare took a step. The Hare took another step. The Hare took another step. The Hare took another step..." Inlined too little: "The race began. The Tortoise won!" It's interesting because some authors actually make mistakes in this realm - overdoing it on details, or leaving the reader confused without enough context. Thinking about the flow of code like the flow of a novel is probably a good idea - both should delicately balance complexity with readability. The best examples of both often describe complex and nuanced concepts while remaining surprisingly straightforward. If you think this example is contrived and it's always obvious where to abstract and where to inline, it's likely you're over-abstracting. The question of "where to cut" varies greatly from one bit of code to the next and often needs some thought to get right. John's list under "To sum up" here is a great set of guidelines to answer that question.
- gustavorg 6y ago"If there are multiple versions of a function, consider making a single function with more, possibly defaulted, parameters." I have years avoiding to do this because there is a known code smell that happens when a function execution changes based on parameters. My personal rule is to be splendid with functions.
- arnaudsm 6y agoI love how Carmack worried about a single frame of input lag, while most modern games have easily >7 frames lag. I expected time would have solved the issue, but it's 2020 and it's worse every year. Same with GUIs.
- skohan 6y agoThis is one of those pieces of writing which I always tend to re-read every time it pops up on one of my feeds. What I like about learning from Carmak's approach to programming is that he's always seemed to work in domains where he had to squeeze every ounce of performance out of what he's doing. I think that kind of programming forces you to focus on what's actually true about computers, and about programming concepts. As programmers, when we talk about design patterns and best practices, a lot of what we talk about actually comes down to opinion, philosophy and aesthetics. When you are really forced to get the right bits to the right place as quickly as possible, it focuses the problem of software design in a very specific way. It's interesting to observe that for Carmak, that appears to be in the direction of removing as much abstraction as possible.
- westwing 6y agoFew remember that the ancients decided to let the stack grow downwards to symbolize descent into the deepest circles of hell.
- troughway 6y agoFrom JC: "the exactly predicted off-by-one-frame-of-latency input sampling happened" I'm assuming this happened because the game, starting with an empty input buffer, queued input for the subsequent frame, rather than use the input as-is and process it right then and there?
- dang 6y agoIf curious see also 2019 https://news.ycombinator.com/item?id=18959636 https://news.ycombinator.com/item?id=18959636 2016 https://news.ycombinator.com/item?id=12120752 https://news.ycombinator.com/item?id=12120752 Discussed at the time: https://news.ycombinator.com/item?id=8374345 https://news.ycombinator.com/item?id=8374345
- stkdump 6y ago> It would be kind of nice if C had a "functional" keyword to enforce no global references. I guess with constexpr, at least in C++, this is a reality now.