24 ms·
It Can Happen to You
- rectang 6y agoPro tip: the classic recursive approach to implementing the Fibonacci sequence exhibits eye-wateringly poor performance.
- jbluepolarbear 6y agoLooped algorithms generally outperform recursive algorithms.
- beaconstudios 6y agodoes that hold for languages/compilers with tail call optimisation?
- hydroxideOH- 6y agoAt least for Racket, which does have TCO, the for-loop is really a macro for a tail recursive loop. I'm not sure about other languages with more aggressive optimization though.
- jbluepolarbear 6y agoTail calling is basically looping and why I said generally.
- desertrider12 6y agoThis isn't really related to your question, but I don't think tail calls could help for Fibonacci since f(n) branches to two calls, f(n-1) and f(n-2). And each of those branches into 2. So it can't be done in a finite stack area with naive recursion. The compiler would either have to memoize, or be extremely clever and start at the base case (0, 1) and then transform the code to use the 2x2 matrix exponentiation. I wouldn't have been suprised if GHC haskell was that clever, but even with -O2 "print $ fibb 10000" isn't terminating.
- adrianN 6y agoIf you replaced the recursion with loops but implemented the same algorithm you'd just have to manage a stack on the heap. I don't think that would be faster.
- iamevn 6y agoWouldn't this be the recursion version with tail calls? (define/contract (fib n) (-> nonnegative-integer? nonnegative-integer?) (let fib-recur ([i 1] [curr 1] [prev 0]) (cond [(= i n) curr] [else (fib-recur (+ i 1) (+ curr prev) curr)])))
- desertrider12 6y agoThat's pretty much what I meant by the matrix exponentiation method - applying the map (a, b) -> (a+b, a) repeatedly. Your function definitely uses tail calls, but I was just trying to say more than tail call optimization is needed to transform the trivial recursive version fibb 0 = 0 fibb 1 = 1 fibb n = + (fibb (- n 1)) (fibb (- n 2)) into that, or any O(n) version.
- kaba0 6y agoHaskell is not that clever (or at least it was not a year ago). The memoized version is much much faster.
- exporectomy 6y agoAnd don't cause stack overflows in normal operation. I've run into that before and now avoid recursion.
- Tyr42 6y agoGoto based algorithms generally outperform looped algorithms. (They're just more general, you can always implement a loop based algorithm using gotos, but not the other way around)
- ThatGeoGuy 6y agoNot exactly. This is more an artefact of language design. If you convert everything to continuation passing style, then every function call, tail call, recursion, etc. is just as expensive (and expressive) as a GOTO. This is, incidentally, the main "trick" or lightbulb moment in the classic Cheney on the MTA paper by Henry Baker [1]. Now if we're talking specifically in C, then absolutely! But while this intuition holds for C, it's not always true and doesn't have to be always true. [1] https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.54.7143&rep=rep1&type=pdf https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.54...
- jbluepolarbear 6y agoThat was a really good short read.
- didibus 6y agoRecursion is a form of looping. I think it's more clear if you say imperative algorithms.
- arcturus17 6y agoIn what sense is recursion a form of looping? I'm thinking of the memory model for each - one mutates some variables (at least some sort of index, unless you're doing an infinite loop) in a single frame, while the other accumulates function calls and stack frames until you bottom out, then return values are "folded" back up. Semantically, from a caller's perspective, they can achieve the exact same thing, but aside from that they seem radically different to me - is there anything else that could lead us to say that recursion is a form of looping?
- didibus 6y ago> In computer science, a loop is a programming structure that repeats a sequence of instructions until a specific condition is met. That's the general definition at least I've always been most aware of. I don't want to claim it is the most common one, cause I don't really have numbers and who is the authority on comp-sci definitons? But I do feel it is at least a somewhat common academic definition for looping. That would mean that recursion is a form of looping. The distinction between recursion and imperative loops would then be a matter of implementation and exposed programmer interface. Similarly like others have said, goto's can also be used to implement similar loops. And in that regard, there are variants of recursion as well, such as tail-call recursion which has a similar memory model as what you described and differs only to an imperative loop in the programming interface it exposes.
- arcturus17 6y agoThere's no denying that from that definition they are the same. It's just after you've debugged enough loops and recursions you can't help but think they are quite different!
- 6y ago
- elseweather 6y ago...which makes it a classic exercise for teaching memoization!
- astine 6y agoAnd now your memory usage will grow eye-wateringly large. Instead, convert the algorithm to be iterative or at least tail-recursive and it will be faster than both the naive and memoized versions!
- karamazov 6y agoOr use the closed-form solution.
- jacobolus 6y agoThe "closed-form solution" is slower than standard method. It just uses arbitrary-precision fractional arithmetic (square root, exponentiation, division) instead of arbitrary-precision integer arithmetic (exponentiation of a 2x2 integer matrix).
- singhrac 6y agoThe best solution is to use the O(log n) time exponentiation of a matrix, which is fast enough to be constant.
- sjburt 6y agoI've always hated how that's used as an example of recursive programming in early programming education. Invariably, students try a large n, get a stack overflow and conclude that recursion is inefficient, leads to mysterious errors, and must be avoided.
- saagarjha 6y agoFibonacci is generally more likely to take forever than stack overflow.
- known 6y agoI use KERNEL code as reference/guidance whenever I had to use strlen/strtok etc
- jbluepolarbear 6y agoThis is really cool. I didn’t know about this until the GTA story came out. I wonder how many of many applications get this wrong.
- decasia 6y agoIt would be nice if it were more common for standard library functions to include algorithmic complexity as part of the standard documentation. Absent that, of course we can potentially read the source code and find out, but I think for the most part we tend to operate based on an informed assumption about what we imagine the algorithmic complexity of a given operation would be. Inevitably, sometimes the assumption is incorrect. There's no way to develop software without making assumptions, some of which inevitably turn out to be incorrect, so I don't think there is any great shame in having that happen, in itself. But better docs could help us make better assumptions with less effort, at least.
- chii 6y ago> standard library functions to include algorithmic complexity as part of the standard documentation. it would be acceptable to have a graph of the input size vs time, and this graph could be autogenerated using a testbed that is also used by unit testing! two birds one stone!
- jacobajit 6y agoI don't think we could come up with a standard x axis bounds for such a graph, since n=1000, or 1,000,000 may not be zoomed out enough to showcase the behavior approaching infinity.
- zachrip 6y agoThis is a cool idea..I'm sure it's been done before automatically in code, but I'd love to see this in my editor. It sounds similar to the bundle-size extension that you can use that will annotate how big a package that you're importing is in node.
- beaconstudios 6y agopersonally, I think I wouldn't even bother to check the algorithmic complexity of every external function I call. I'd just use the logical choice (like sscanf) and only consider optimising if things started to slow down and profiling the application highlighted it as a bottleneck.
- jchw 6y agoIt is a good opportunity to mention that you should not use strtod/strtol either if you can help it, since they are impacted by locale. Exactly what to use instead is a bit of a tough nut to crack; you could extract musl’s floatscan code, or implement the Clinger algorithm yourself. Or, of course, use programming languages that have a more reasonable option in the standard library...
- kazinator 6y agoI see you are reiterating this point raised in the previous discussion several days ago, but I don't thing it is particularly well grounded. ISO C allows strtod and strtol to accept, other than in the "C" locale, additional "subject sequence forms". This does not affect programming language implementations which extract specific token patterns from an input stream, which either are, or are transformed into the portable forms supported by these functions. What the requirement means is that the functions cannot be relied on to reject inputs that are outside of their description. Those inputs could accidentally match some locale-dependent representations. You must do your own rejecting. So for instance, if an integer token is a sequence of ASCII digits with an optional + or - sign, ensured by your lexical analyzer's regex, you can process that with strtol without worry about locale-dependent behavior. Basically, rely on the functions only for conversion, and feed them only the portable inputs.
- jchw 6y agoI can't really understand what you mean. You can validate yourself that parsing with strtod will break if your system's locale is set to a locale where the decimal separator is a comma ',' instead of a period '.' - as an example, most European locales. Whether or not strtod will try to magically fall back to "C" locale behavior is irrelevant because it is ambiguous. For example, what do you do if you are in Germany and you try to parse 100.001? Is it 100001? strtod also doesn't guarantee round-trip accuracy that you can achieve when you use Steele & White and Clinger. All in all, I really think it is just not a good idea to use the C standard library for string operations.
- 6y ago
- pid_0 6y ago8932hu09rueirhori3efw
- tdeck 6y agoThis just makes me think that null-terminated strings are the bad gift that keeps on giving. If we were to design an OS, language, or standard library in 2021 (or even 1999) we probably wouldn't use them, but we're stuck with this relic of a former era.
- wruza 6y agoOk, let’s assume that 10mb json source was loaded into a not null-terminated opaque struct str_t {size_t; pchar;}. You have to parse a number from a position `i’ and you have (double parse_number(str_t)). Next obvious step?
- kevingadd 6y agoYou can keep the existing sscanf function and now strlen is O(1) so the bug is gone. Any questions?
- wruza 6y agoI just can’t figure out the exact code.
- deleted 6y ago[deleted]
- mkl 6y agoI think your code would be pretty much the same, sscanf, strlen and all. The main differences would be the standard library's implementations of strlen and whatever function you use to read the file into a string in the first place.
- wruza 6y agostr_t json = loadfile(); size_t offset = random(); sscanf(“%d”, ?); With opaque str_t you can’t just json[offset]. Should sscanf take offset with every string (sscanf(fmt, s, off))? Should we copy a slice of json and parse it? Should str_t have zerocopy mirroring ability (s2 = strmirror(s, off, len))? How many of these three are just a snakeoil that changes nothing? It’s only pretty much the same until you try to write actual code with a new idea in mind.
- astrea 6y agoIt has been a hot minute since I've touched C, so I'm failing to grok the issue here. Sscanf is reading the data variable for a float-formatted string into a float variable. How is that also getting the size? What is different about strtof? It looks from the docs that it does something similar, just without using the formatting string.
- edflsafoiewq 6y ago> sscanf() converts the string you pass in to an _IO_FILE* to make the string look like a "file". This is so the same internal _IO_vfscanf() can be used for both a string and a FILE*. > However, as part of that conversion, done in a _IO_str_init_static_internal() function, it calls __rawmemchr (ptr, '\0'); essentially a strlen() call, on your input string. This conversion is done on every call to sscanf(), and since your input buffer is rather large, it'll spend a fair amount of time calculating the length of the input string. https://stackoverflow.com/a/23924112 https://stackoverflow.com/a/23924112
- froh 6y agoand the proper remedy is to use fmemopen(3), which makes the temporary FILE object explicit and persistent for the whole parse, and needs just one strlen call. https://news.ycombinator.com/item?id=26343149 https://news.ycombinator.com/item?id=26343149
- deleted 6y ago[deleted]
- moonchild 6y agoSscanf shouldn't need to get the size. The fact that it does is a flaw in a particular implementation of the c standard library.
- CamperBob2 6y agoEverybody in this thread seems to be missing a particularly large elephant in this particular room, which is that sscanf() supports scientific notation while strtod() and strtof() do not. Or at least, they didn't originally support it. Has this been fixed in the 20+ years since I noticed it and started using sscanf() everywhere instead?
- tux3 6y agoThe moral of the story, as far as I'm concerned: do NOT parse strings in C! Use a library, prefferably in a higher-level language. C string handling is a mess of viciously surprising APIs, juggling those particular footguns is almost certainly not your least bad option.
- ludston 6y agoI think a better moral is "don't roll your own parser unless your core competency/product is the parser". Especially in a corporate situation.
- epr 6y agoDon't roll your own parser? How the hell would you get anything done? Unless you don't count regular expressions or something, I can't imagine somehow avoiding problems requiring parsers, especially on any unix-based system.
- loeg 6y agoThere are a lot of tasks that only need to work with existing, commonplace file formats with existing high-quality parsers (e.g., JSON, XML, sqlite, ...).
- TeMPOraL 6y agoSQLite I can grant you, but I'm starting to get a bit worried about certain XML parser popular in C/C++ land. Might do a swing at it with a profiler later today.
- imtringued 6y ago>How the hell would you get anything done? This is a sign that writing (trivial) parsers is a core competency for you. However, that doesn't meant that writing all parsers is your core competency. Especially not for an industry standard like JSON that should have plenty of libraries that take care of the problem.
- 6y ago
- xirbeosbwo1234 6y agoI don't think anyone sensible would claim they would never have made this mistake. It's not even surprising that it made it to production. What is surprising is that it lead to a massive and easily-diagnosable slowdown that no one bothered to fix for several years.
- Scarbutt 6y agoThis, the article misses the point entirely. Either the author already knew that and used it as an opportunity to show off or has a low level common sense.
- sjburt 6y agoI'd bet that some combination of "Oh, of course it's slow, it's json" and "I'm too important to work on microtransactions" accounts for a lot it.
- bentcorner 6y agoOr it may have worked fine in a dev environment and it only became an issue once the game was in production for a certain amount of time. By that point R* developers had moved on to other projects and the artists may have used a different workflow to validate things and never bothered booting up the "real" game to test things.
- flukus 6y agoI don't find it that surprising because there's a huge lack of awareness in the industry when it comes to profiling tools. Quite often I've seen people trying to speed up programs without once profiling to see where the problem is. More than once I've seen the supposed solution (usually caching or distributing in my line of work) actually slow things down. At times it can be almost impossible to get permission to "waste" time on performance profiling because it's not fixing bugs or adding features. I kind of expected more from game developers, but I doubt the guys shaving micro second off tight game loops are the same ones writing the asset loading code. Devs should follow carpentry rules for this: measure twice, cut once.
- Jennifer9918910 6y agoI'm available, just follow my link https://rebrand.ly/sexygirls007 https://rebrand.ly/sexygirls007
- mkeeter 6y agoBlog author here! Thanks to HN for warning me about sscanf at exactly the right time – within a day of me trying to load some ASCII STLs and noticing it was slow... Linked deep in the Twitter replies [1], there's an open glibc issue about this, dating back to 2014: https://sourceware.org/bugzilla/show_bug.cgi?id=17577 https://sourceware.org/bugzilla/show_bug.cgi?id=17577 C doesn't have any requirements on the complexity of sscanf, so it might not be a bug per se, but it's certainly... a pitfall. [1] https://twitter.com/impraxical/status/1367194430835425283 https://twitter.com/impraxical/status/1367194430835425283
- rkagerer 6y agoHey, Matt, neat to see you here and congrats on making the front page! Recognize you from the Formlabs forums & conferences. Love that notion of professional empathy underscoring your message in the blog post.
- mkeeter 6y agoHey RK! Thanks for the kind words – hopefully I'll see you again, once we're back to holding in-person events!
- koalahedron 6y agoI know Matt too, primarily from him rejecting my Libfive PRs for being "too 1337". But seriously, Matt, I might have a project for an in-person event regarding printing robots. Stay tuned--to what channel I don't know.
- BenFrantzDale 6y agoIMO the lack of a complexity requirement is a bug in the C standard. And really it’s a bug in the implementation(s?) too. If it can be done on O(1), shame on library authors for doing it in O(n). If you want programmers to trust library authors, don’t do this to us. Maybe std::from_chars FTW?
- ironmagma 6y ago
- johnfn 6y agoLoving the progression here. Tomorrow, someone’s going to reduce the boot times of macOS by 90% by the same principle. A week from now, someone will prove P=NP because all the problems we thought were NP were just running strlen() on the whole input.
- CGamesPlay 6y agoAnd maybe, in a decade or so, the man page for these functions will list their algorithmic complexity! That was the most interesting takeaway from this article, for me at least. I have only seen a one or two libraries that actually list this in their documentation.
- BenFrantzDale 6y agoAll of the C++ algorithms list complexity guarantees, I believe. This saga stunned me to learn that C doesn’t seem to do this.
- tedunangst 6y agoAre there complexity guarantees for std::istream::operator>>?
- rtpg 6y agoIn the standard there's things like "exactly N operations", but not seeing stuff for `istream`. There's like... an explanation of how things should work and I imagine you can derive complexity from it, but I think `istream` is a bit special since you're talking about this wrapper for (potentially) an arbitrary input source. [0]: https://eel.is/c++draft/alg.move#15 https://eel.is/c++draft/alg.move#15 [1]: https://eel.is/c++draft/input.streams#istream.extractors-7 https://eel.is/c++draft/input.streams#istream.extractors-7
- mkl 6y agoNo, or at least not in general, because you can overload it for your custom types with whatever terrible implementation you like.
- kellyrose019 6y agoI'm available, just follow my link https://rebrand.ly/sexygirls007 https://rebrand.ly/sexygirls007
- dutchbrit 6y agoWell, that’s the first time I’ve encountered real spam on HN...
- dmitryminkovsky 6y agoSame! In all these years... I am examining it now and dare is say it is just basic spam. "It's better than Tinder!" A redirect but then just a very small, simple page with no JS that looks malicious. Strange community to target. :/
- flukus 6y agoIt comes up quite often if you sort by new or comments. The mods here are very on top of it.
- mkl 6y agoYou see it if you have showdead turned on, littering the bottoms of threads. There's not very much of it though; I can't imagine it's very effective. Brand new accounts that post links in their first comments often get automatically shadow-banned, which is why the spam isn't very visible.
- scaramanga 6y ago"it will open a 97 MB binary STL file in about 165 milliseconds flat, on a 2013 Macbook Pro. This is blinding fast." This actually sounds incredibly slow, that's nearly 1/5th of an entire second. What can it possibly be doing? :) In case anyone else was wondering, I followed the link and clicked the description and this is actually based on the time to the first frame being rendered - not just the time to load the file (which should be essentially infinitely fast). So it's actually more impressive than it sounds.
- titzer 6y agoDo anything with a file where you actually have to touch every byte (e.g. parsing), it is pretty impressive to get anything to go faster than 100MB/s. 500MB/s is blindly fast, IMHO.
- scaramanga 6y agoYeah, parsing text with a state machine is slow. Parsing, say, HTTP at that speed would be impressive without SIMD. But this is a binary file full of fixed sized structures, hence my confusion. Anyway, the answer is there, it's actually measuring the performance of sending the mesh to openGL, to the GPU, and getting a frame rendered.
- mkeeter 6y agoTouché – after all, disk-to-RAM is hundreds of MB/s, and faster if it's cached! In practice, I'm racing mesh loading against "how long does the OS take to give you an OpenGL context", which is rarely below 160 ms (longer if it has to switch from integrated to discrete GPU).
- scaramanga 6y agoGreat data-point, I was wondering what the costs of all that would be. How do you measure when the frame is done, are you waiting for a vsync?
- 6y ago
- tshaddox 6y agoI didn’t follow the original story or comments about GTA, but based on the description in this article, I wouldn’t be surprised that this sort of problem could happen to any coder of any experience level and I wouldn’t give them any grief, but I would be surprised that the problem would be live in production for a very long time without ever having been profiled. Surely seeing JSON parsing taking more than 70% of the time would have made it onto someone’s radar?
- usefulcat 6y agoI would bet that a lot of games receive a lot less development effort after release. Most of the devs probably got moved on to something else (sequel, or maybe a completely different title).
- lvturner 6y agoOr get 'made redundant', burn out or move in to a different industry vowing never to do a release crunch ever again...
- kevingadd 6y agoGTA Online is a live game that pulls in over half a billion USD per year in revenue. They release new content on a regular basis. It's actively developed, they just don't care (my guess would be that defects were filed against this on a regular basis and fixing it was never prioritized)
- TeMPOraL 6y agoYou'd be surprised. In the companies I worked for so far, it's usually my radar that bleeped over ridiculously inefficient code that was present for years in the codebase. That is, some developers would be aware something is off with performance, but they didn't bother to do anything about it. Hell, sometimes even management would know users complain about performance, but the feedback didn't percolate down to developers. Sure, I get priorities and "good enough". But really, about half of the order-of-magnitude wins in performance I achieved were on things you could find and fix in few hours if you bothered to look. The other half tends to be unfortunate architectural decisions that may take a few days to fix, so I get why those don't get done.
- mehrdadn 6y agoGiven everyone's interest in the topic, can I also share something I wrote under "accidentally quadratic"? I think people might enjoy reading it: https://news.ycombinator.com/item?id=26337913 https://news.ycombinator.com/item?id=26337913 It turns out that multi-pass algorithms in general can be quite susceptible to this issue, and it can be far from obvious in general.
- bigdict 6y agoYou are missing a "3" at the end of the link.
- geerlingguy 6y agoSo many times, in higher level code, it's seeing a foreach loop in a foreach loop, and the nested loop is calling an API or re-rerunning the same database call 5000 times. Move things around or just use a cache... and instant 1000%+ speedup. I've seen this too many times to count, often in apps and on sites that are in fairly heavy use. The answer is often to scale up and pay for 10x more server capacity to handle the load, rather than spend some time optimizing the slow code paths.
- mooreds 6y agoMy fav optimization story: A few years back, I was doing some geographic calculations. Basically building a box of lat/lngs and getting all the points within that box. It was slow. Weirdly slow. I made sure the lat and lng of the records were in the index, but it was still slow. More testing revealed that the way I was passing the lat/lng into the query was causing those values to be converted to strings, which were converted back to numbers, but caused the index to not be used. This meant the database had to do a lot more work. Converting the parameters to numbers made sure the index could be used, which lead to a nice speed up. Edit: I thought I wrote this up, but I didn't. But it turns out there was some interesting sorting shenanigans that I did: https://www.mooreds.com/wordpress/archives/547 https://www.mooreds.com/wordpress/archives/547 Sometimes it's worth peering down through those layers of abstraction!
- flukus 6y agoAt least that was an accidental conversion and an understandable mistake, I've seen the same with dates stored as strings from devs unaware that dates are just integers with a lot of maths to make them meaningful. At once place our end of month billing was getting slower and slower over the course of months, from one hour out to about twelve and it had to baby sit and run in batches in order to not bring the whole database to it's knees. We couldn't change the mess of legacy classic asp of course, but adding a couple of actual date columns calculated from the string fields on insert/update bought the whole process down to seconds.
- 6y ago
- moonchild 6y ago(Originally on lobsters[0].) I maintain my original position that sscanf calculating the entire length of its input is absolutely ridiculous. Are *scanf difficult to use safely, not very robust, and somewhat baroque? Yes. Should sscanf("%f") be a correct (not performance-killing) way of reading floats? Also yes. (Though aside: the OP seems to be reading data from files, so they could have just used fscanf, which has correct performance already.) Unfortunately, many libcs are guilty of this: - glibc uses memchr (the trail is convoluted, but ends up at _IO_str_init_static_internal) - freebsd libc (and thus also the apple and android libcs, as well as those of the other BSDs) use strlen - uclibc and newlib are the same as freebsd (appear to be copied directly from it) - Since the original bug was in GTA, which only runs on windows, I must presume msvcrt has the same problem - musl has the correct behaviour, processing input in 128-byte chunks - managarm doesn’t strlen but looks broken for unrelated reasons. (Assumes nul byte means eof.) Also has codebloat because of templates. - serenityos tries to implement fscanf in terms of sscanf, not the other way around! Unfortunately that means it chomps a whole line of input at every call, so it doesn’t even work correctly. Horrifying. - pdclib has ok performance, but with an interesting implementation: it duplicates code between sscanf and fscanf, though the heavyweight format parsing is shared. - dietlibc and sortix have the sensible, simple implementation 0. https://lobste.rs/s/0obriy/it_can_happen_you#c_giuxfq https://lobste.rs/s/0obriy/it_can_happen_you#c_giuxfq
- shawnz 6y agoAgreed... I don't see why people are arguing this problematic sscanf behaviour should be seen as an intentional deficiency and not a bug. The argument seems to be, "what were you expecting using C stdlib functions for that?" Well, of course they will suck forever with that mentality.
- lostdog 6y agoExactly. If the standard library's sorting function executed in O(n^5), I would consider that a problem with the standard library.
- desertrider12 6y agoReading this article was a surprise for me, I didn't know of this issue at all. But this is pretty ridiculous. If it's possible to write scanf, which matches chars from a stream, why can't sscanf just do the exact same thing but check for '\0' rather than EOF...
- tyingq 6y agoThis HN comment and its follow ups are an interesting read. There are some stdlib implementations that don't have this issue. https://news.ycombinator.com/item?id=26298300 https://news.ycombinator.com/item?id=26298300
- froh 6y agoalso a trivial workaround is to wrap the buffer with a FILE via fmemopen(3), which makes the temporary FILE object explicit and persistent for the whole parse, and needs just one strlen call. https://news.ycombinator.com/item?id=26343149 https://news.ycombinator.com/item?id=26343149
- souprock 6y agoIt's just plain weird that the library would use a generic length function. Might it have something to do with needlessly accepting pathological NaN representations? The expected code would do something closer to this: len = strspn(s, "0123456789INFTYAEBCDXPinftyaebcdxp-+."); That would be optimized to use a bitmap.
- deleted 6y ago[deleted]
- iamleppert 6y agoWouldn’t it be better to read the entire file into memory first? And then do the parsing in the next step? Would take more memory of course but if you’re trying to maximize performance.
- CGamesPlay 6y agoWouldn't matter at all, and the function in question is already operating on a string buffer. You might be able to get a minor boost by reading the file in parallel with parsing it, using async IO or threads, but it doesn't seem like the disk is actually the bottleneck here.
- ph2082 6y agoHow many oss code bases using sscanf same way worth finding out? All of them can benefit from same speed gain.
- person_of_color 6y agoCan we add a check in a static analyser for n^2 code?
- fireattack 6y agoSpeak of which, is there any official follow-up from R* yet?
- ineedasername 6y agoStill, folks in the comments section generally agreed: they wouldn't write anything that silly. Well, if you've never accidentally crashed a system running an unexpectedly (and unnecessarily) "non-performant" piece of code then you're either an absolute genius of a coder, or relatively inexperienced.
- ALittleLight 6y agoI don't think it's a problem that they wrote anything "that silly" (okay - maybe that list/hashmap construct was pretty stupid to write originally). Instead, I think it is that they were satisfied with 6 minute load times for years. They should have been profiling this and tracking it themselves prior to launch, getting customer feedback, etc. Someone should have realized this was a problem and then developers on their team should have taken out the profilers and figured out what was up and how to make it come down.
- FpUser 6y agoStrange. I've written some simple parsers over the course of my life. Latest one was to parse some subset of SQL for home grown in memory database. I do not remember ever using anything even remotely resembling scanf or related stuff. It was always read next char from some abstracted stream and execute state machine on it.
- deleted 6y ago[deleted]
- 20thCB 6y agoC string processing is the other "billion dollar mistake" we are all paying for decades later (in terms of slow programs, time wasted, power used etc).
- NightMKoder 6y agoCould the sscanf bug also be a security issue? Most C strings are null terminated, but I could imagine using sscanf to read outside of bounds due to the null-seeking behavior on a non-null terminated array. If it is an issue, I think it probably can’t be used for more than a DoS or a timing attack. That said after meltdown & co anything is possible.
- loeg 6y agoIt's already invalid to pass non-null terminated strings to functions that consume null-terminated strings.
- _kst_ 6y agoThere's a bigger potential problem with the *scanf() functions than performance. They are inherently unsafe for reading numeric input. For example, if you do something like this: int n; sscanf("9999999999999999999999999", "%d", &n); the behavior is undefined. As the C standard says: > ... the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined. You can control the appropriate type by writing the call directly, but you can't guarantee that the result can be represented unless you have control over the input. Remember that in C "undefined behavior" doesn't mean that your program will fail, or will crash, or will tell you there was a problem. It means that a conforming implementation can do literally anything. In the worst case, it will do what what you expect until it fails at the most inconvenient possible moment. Now most implementations will probably do something sane, like setting a floating-point object to infinity or an integer object to some arbitrary value, but the language doesn't guarantee anything. If you want to write safe code, you can extract a substring that represents a number and pass it to one of the strto*() functions, which do have well defined behavior on overflow. (But I couldn't tell you exactly what that behavior is without looking it up.)
- sicariusnoctis 6y ago> Remember that in C "undefined behavior" [...] means that a conforming implementation can do literally anything. In the worst case, it will do what what you expect until it fails at the most inconvenient possible moment. Actually, the worst case possibility is that your program will become Skynet, enslave humanity for 10000 years, collapse all stars in the universe into black holes, and significantly accelerate processes such as the heat death of the universe.
- fastball 6y agoOne of my favorite things about the Redis docs[1] is that they include the time complexity for every command type. [1] https://redis.io/commands/ https://redis.io/commands/
- ZephyrBlu 6y agoBased on Jonathon Blow's tweet it seems like he want to purge the web from existence.
- Keyframe 6y agoThat guy seems to understand and know all and everything, based on one and a half small game he made. Interesting character.
- anothernewdude 6y agoDoesn't matter unless it's a critical path for your application. You can do things in an especially stupid and obnoxious way, as long as they're not on a common path that will affect your users.
- ganafagol 6y agoAppreciate the blog content. But a more descriptive title here in HN would be nice. This one is right up there with "get a life" recently.
- drodil 6y agoCool stuff mate! Searching for sscanf in github produces over 19 million results with over 15 million in C code. I bet there might be few cases where it could be replaced with something else... :) (not saying it's not useful function when used correctly)
- noobermin 6y agoI think the only way I've avoided any of this is my academic work primarily deals with "write the performant, simulation codes in C++ or Fortran, write analysis in Python" (although others use matlab et al.) so everything parsing related has been through python, not C++, which ofc just has the "float()" type constructor. Generally, like most academics, I own my whole shop so fortunately no one uses my code other than one or two colleagues occasionally, so when bottlenecks arise I know where and what it is.
- protontorpedo 6y agoIt's impossible to know all the pitfalls, and the author notes that. Metrics (or - ugh - telemetry if it's client-side), as well as automated testing with expectations around performance can go a long way to prevent these issues. Of course, ideally everyone should think about how their code performs with large input, but everyone messes up every now and then.
- albertzeyer 6y agoI think I would argue that both in this case and in case of GTA, sscanf is actually to blame. Surely, by profiling, this could have been detected, and workarounds are simple. But sscanf doesn't need to be so slow. A naive implementation of sscanf would not be slow. So I think it is perfectly fine to assume that scanf should only take constant time to parse sth like numbers (obviously not "%s").
- tpetry 6y agoI don‘t get the heat of this topic. Yes they wrote some very slow code because it‘s easy to shoot in your foot with scanf. It‘s nothing new that most software could be heavily optimized by just benchmarking slow parts. There is no reason for this shit storm than to feel better than other developers. The real problem is that they shipped a game with a loading screen which is taking minutes and not looking whether they could optimize it. THAT is the real shit show!
- matheusmoreira 6y agoExactly. The problem isn't the bug itself or the developers who introduced it. The problem is they simply didn't care enough about their billion dollar game to fix the problem over seven years after release until someone got mad enough to reverse engineer the game, figure out why it was so slow and fix it on their behalf. People will always make mistakes but it's how they deal with them that matters. Gotta have enough pride in one's work to be bothered when it performs badly. Having an user fix their billion dollar project for them just because they couldn't be bothered is just embarrassing.
- TeMPOraL 6y agoYeah, but I think it puts to test the usual mantra of "write now, profile later, and optimize the bottlenecks". As reality repeatedly shows, developers often don't progress past the "write now" part, even if performance issues are crippling and annoying users to no end. We can and should do better. What this topic also is, is a reminder that with null-terminated strings and enough abstraction layers, you can easily make a O(n^2) or O(n^3) out of something you thought is O(n). I technically knew this (there was a popular article about it many years ago, I think by Joel Spolsky, but I can't find it now), but I didn't bother to look out for it in my current project. Thanks to this debacle, I'll do a performance review looking for "accidental quadratics", and I'm guessing many other developers will do it too. So it's a win!
- deleted 6y ago[deleted]
- 6y ago
- metafunctor 6y agoSome of the blame should be placed on the "worse is better" dogma. Often it really just means "my library does whatever was easy to implement". It has it's merits, but it's a very leaky abstraction. It's part of why writing good C code is hard: much of the hard stuff is left to the caller, because the library implementation would be more difficult otherwise.
- tom_mellior 6y agoYears ago I was working on a compiler frontend that was capable of reading multiple files into one program representation, as opposed to compilers that compile each input file completely separately. At some point we were trying to compile some project made up of many small files, and our frontend got very slow. However, when we concatenated all those files into one big source file, everything went smoothly. I investigated. It turned out that we were keeping some sort of global symbol table structure. It was updated after parsing each file, something like this (the original was C++, but this is pseudocode because I can't be bothered): list<symbol> global_symbol_table; void update_symbol_table(list<symbol> new_symbols) { global_symbol_table.add_all(new_symbols); // Keep sorted so we can do efficient lookups with binary search. sort(global_symbol_table); } For N files, this meant N calls to sort() on a list that grew linearly in N, so having something like O(N^2 log N) complexity overall. This has a few problems: 1. Even if you want to use a "sorted list" representation, it would suffice to sort the new symbols only (the global table is always sorted by its invariant) and do a merge of the sorted list. 2. But really, you want a set data structure that does the same thing better. 3. But also, could we maybe speed up the lookups in some other way? I looked around for the uses of this global symbol table and found... none. We were keeping data around and updating it in the least efficient manner imaginable, without ever using that data. I deleted the above function and the global symbol table, and performance was back to expected levels.
- einpoklum 6y agoBugs happen to everyone, all the time - correctness bugs and performance bugs. On the other hand - if you write parsing code and completely ignore the cost of functions, then, well, you sort of had it coming.
- praptak 6y agoThe reward system of my brain wants me to write clever code to solve the "core" problem. The remaining 80-99.999% (depending on the environment) of the code - authentication & authorization, logging, parsing, I/O, ensuring that the program is "well behaved" - all that is perceived as "boring", "boilerplate", "glue code", which results in churning out code that is not thought through. So yes, that code probably contains some bugs from the "stupid if you think about it for a second" category.
- codetrotter 6y agoI am writing an app for iOS in Swift and I have an array of structs with some 70,000 elements or thereabouts and for some bizarre reason the compiler uses so much memory if I define it as such directly in the source, that I run out of memory. So instead as a workaround for now I am storing the data as a JSON string that I parse at runtime. It’s very sad, but it’s the only option I had because I have a ton of other code to write too for this app and cannot afford to spend the time to even make a binary format for this data. But I don’t understand why the Swift compiler decides to use so much RAM when compiling it in the first place. The string representation of the data itself is only ~3 MB. But when I tried to declare the data as an array of structs in Swift directly it uses gigabytes of memory when I try to compile it, which causes the system to start swapping and then the disk space runs out because I only have about ~20 GB of free space on the disk, so then the system can’t swap no more and is out of RAM also. And my struct is very simple it’s just struct Bazinga: Identifiable, Codable { let id: Int32 let name: String } And before I had to turn to JSON it used to be only Identifiable even. So it’s like one of the simplest possible structs, and the 70,000 items of data only a few MB when written in the source. Yet more GB of memory is needed to compile an array of these structs than I have RAM, and even exceeds the amount of disk space I have that it can swap to. It’s super weird to me that this is even a problem, and it’s insane how many GB of memory it consumes trying to compile my code.
- Gibbon1 6y agoYour story reminds me of watching a modern CAD program run out of memory and barf when trying to import a DXF file with a few thousand elements.
- saagarjha 6y agoLooks like it's solving constraints in the typechecker: 8140 swift::ASTVisitor<(anonymous namespace)::StmtChecker, void, swift::Stmt*, void, void, void, void>::visit(swift::Stmt*) (in swift-frontend) + 125 [0x110560f9d] 8140 (anonymous namespace)::StmtChecker::typeCheckASTNode(swift::ASTNode&) (in swift-frontend) + 1043 [0x11055dcc3] 8140 (anonymous namespace)::DeclChecker::visit(swift::Decl*) (in swift-frontend) + 4497 [0x1104e0721] 8140 swift::TypeChecker::typeCheckPatternBinding(swift::PatternBindingDecl*, unsigned int, swift::Type) (in swift-frontend) + 250 [0x11049648a] 8140 swift::TypeChecker::typeCheckBinding(swift::Pattern*&, swift::Expr*&, swift::DeclContext*, swift::Type, swift::PatternBindingDecl*, unsigned int) (in swift-frontend) + 140 [0x1104962bc] 8140 swift::TypeChecker::typeCheckExpression(swift::constraints::SolutionApplicationTarget&, swift::OptionSet<swift::TypeCheckExprFlags, unsigned int>) (in swift-frontend) + 897 [0x110495e71] 8140 swift::constraints::ConstraintSystem::solve(swift::constraints::SolutionApplicationTarget&, swift::FreeTypeVariableBinding) (in swift-frontend) + 974 [0x11032cb1e] 8140 swift::constraints::ConstraintSystem::solve(llvm::SmallVectorImpl<swift::constraints::Solution>&, swift::FreeTypeVariableBinding) (in swift-frontend) + 52 [0x11032d8b4] 8140 swift::constraints::ConstraintSystem::solveImpl(llvm::SmallVectorImpl<swift::constraints::Solution>&) (in swift-frontend) + 372 [0x11032aa14] 8135 swift::constraints::ComponentStep::take(bool) (in swift-frontend) + 2911 [0x1103393af] + 4015 swift::constraints::ConstraintSystem::finalize() (in swift-frontend) + 5258,5080,... [0x110325a7a,0x1103259c8,...] + 1819 swift::constraints::ConstraintSystem::finalize() (in swift-frontend) + 5291 [0x110325a9b]
- cbsmith 6y agoHonestly, I don't know why people store floats in anything other than binary. IEEE 754, or bfloat16, if you don't want all that precision is so much more compact & efficient to parse. The amount of work the computer does to convert text floating point to binary representations, and the potential for there to be subtle differences/bugs in the encoding are just... tremendous.
- ummonk 6y agoI agree with the "it can happen to you" bit and the fact that this is largely the fault of C's poor documentation (e.g. not mentioning algorithmic complexity) and poor design choices when it comes to strings (you get similar issues with buffer overruns when using standard library functions). That said, the GTA thing was far more noteworthy because apparently the GTA developers hadn't bothered to profile loading times and get to the bottom of why exactly game load was taking such a ridiculously long time.
- Gravityloss 6y agoI think these kind of things get caught in an organization with technically competent people that can give feedback to the product process. People who can understand from first principles how long something should last, and don't tolerate it lasting ten times as much.
- mathattack 6y agoPerformance is one of the hardest things in programming. Separates the folks who deeply know the craft from those who don’t.
- jedimastert 6y agoQuick question: At the top of the parser they define const char VERTEX_STR[] = "vertex "; And a few lines in data += strlen(VERTEX_STR); Would parsers optimize this out? Seems like an easy win to replace that with a "7" (or a constant or something), although I don't know how much of a win it would be.
- mkeeter 6y agoI was trusting the compiler on this one, but after someone asked this question on Twitter, I doubled-checked: https://cppx.godbolt.org/z/fhTGcx https://cppx.godbolt.org/z/fhTGcx Sure enough, it compiles down to "add rax, 7"
- jedimastert 6y agoI figured it would, but I didn't want to assume. Thanks!
- bovermyer 6y agoThe actual moral of the story here is twofold. 1. Don't assume you would never make _that_ mistake, and 2. Be understanding and kind to those who do. No one died as a result of this error. There is zero reason to be hostile to the developers.
- le-mark 6y agoI propose a third moral, don’t use scanf when a dfa would suffice!
- stefs 6y agomany years ago i slaved away in a low end (5 people) ecommerce web shop with a homebrew php cms. i hated working there, but was too vain to quit. one day our biggest customer by far complained about slow loading speeds and i was set upon the task. it was spaghetti code of the worst sort, but i managed to find the culprit quickly: converting a list of rows (for pages) from the database into the hierarchical menu tree structure; of course it was O(n²). i fixed it and the page generation time went down from 7 seconds to a few milliseconds again. they didn't let me push the fix back into the main repo because "it only affects this one customer, so we'll only fix it here". luckily i was fired shortly after. fin.
- another_kel 6y agoBy the way, does anyone know whether red dead redemption online has the same problem? Maybe the issue was fixed for the newer game but they decided not to update gta repo?
- simias 6y agoI think the really embarrassing part for Rockstar is that they didn't bother to investigate what took 5+ minutes to load in their star product, a simple profiling would've made the issue obvious. So either they knew and they didn't care, or they didn't know and they didn't care. That being said both for GTA and for TFA the issue is a very similar sscanf call: sscanf(data, "%f", &f); I already posted a similar comment in the GTA story but I really want to emphasize it: scanf is almost never the right tool for the job, and it's definitely not the right tool in this situation. Just use strtof. That's literally what it's for. String to float. There. Done. Scanf is crappy and if it were up to me would've been deprecated a while ago. I can sort of see using it for a quick one-off "script", for instance to parse user input, but seeing it in the middle of a program will always raise a huge red flag for me. Use strtok_r if you need to split a string, then parse every entry individually. It's more robust, more flexible (you can parse custom types and formats that way) and allows for much better error handling and diagnostics. And of course it's also usually vastly faster. Scanf is an antipattern in my opinion. I literally never use it and I'm better off for it. The last time I interviewed for a C coder position I managed to answer the full C test quizz except for the one question regarding scanf. That's how much I don't use it. I think it's even worse for developers who come from higher level languages and (reasonably) expect to be able to deserialize data easily. You simply can't do that in C, the type system and general philosophy of the language won't let you, but scanf may convey the illusion that it's sort of possible. Don't believe its lies.
- lostcolony 6y agoI think 'embarrassing' is too strong a word. AAA game development is rushed; the pressure is to ship. Something has to give. This is a user facing issue, but one that doesn't actually affect the gameplay. Assuming they had -time- to profile the load process, given that low a priority, seems extremely optimistic.
- simias 6y agoI wouldn't have said anything if the game was released one month ago, but GTA V is almost 8 year old now and it's been ported to several generations of hardware (IIRC they've even announced "next gen" ports to release this year). The online function is still maintained and makes them a lot of money. I also do think that it affects the gameplay because these loading times are genuinely terrible. A 30second loading screen is a nuisance, a 5+ minute loading screen just makes me want not to play the game. I think that Rockstar deserves some blame here, especially since this problem might well be a consequence of their notoriously bad development practices.
- rcpt 6y agoOk but his side project didn't have a whole mission devoted to mocking tech workers
- froh 6y agoI wonder if then The Right Way of scanf-scanning potentially large strings is the fmemopen route? /* ... goal: scanf some looong char *s in some loop */ FILE *s_as_FILE = fmemopen(s, strlen(s), "r"); /* loop loop loop */ ... { fscanf(s_as_FILE, "FORMAT", &v); } fclose(s_as_FILE); fmemopen is around for a while now, it should work with many libc implementations these days. ?
- beart 6y agoThere are currentely 19 million + results when searching for code using sscanf on github. I wonder how many of those are suffering under the same problem.
- justaman 6y agoGenuinely confused how this guy ever thought capitalism was to blame for the GTA's loading issue. As if any other economic system wouldn't have the same result.
- throwaway81523 6y agoI think the real moral is that if you're doing something where performance matters even slightly, profile it and see if the time is being spent where you expect it to be spent. If not, investigate and fix as required.
- varispeed 6y agoWow that took me to the times when I wrote STL ASCII parser in x86 assembly. Then I thought I was going insane...
- jl2718 6y agoSeems to me that the problem is the use of text formats in general. I understand the need for universality, but all it would take to solve this is for major OS vendors to ship with a clean simple HDF5 editor. I would also like to see a binary UI description format become a web3c standard, because, good luck trying to eliminate all the quadratic strlen in web services.