{"id":42833,"date":"2018-05-29T12:00:37","date_gmt":"2018-05-29T16:00:37","guid":{"rendered":"http:\/\/shamusyoung.com\/twentysidedtale\/?p=42833"},"modified":"2018-05-29T14:11:11","modified_gmt":"2018-05-29T18:11:11","slug":"unity-week-9-preemptive-premature-optimization","status":"publish","type":"post","link":"https:\/\/www.shamusyoung.com\/twentysidedtale\/?p=42833","title":{"rendered":"Unity Week #9: Preemptive Premature Optimization"},"content":{"rendered":"<p>&#8220;Premature optimization is the root of all evil.&#8221;<\/p>\n<p>That quote by <a href=\"https:\/\/en.wikiquote.org\/wiki\/Donald_Knuth\">Donald Knuth<\/a> gets repeated a lot in programming circles. <a href=https:\/\/en.wikiquote.org\/wiki\/Donald_Knuth#Computer_Programming_as_an_Art_(1974)\">It dates back to 1974<\/a>, which means that by the standards of computer science it&#8217;s more or less the Code of Hammurabi. While I freely admit that Knuth is a better computer scientist when he&#8217;s fast asleep than I am at the peak of a caffeine high, I do have some reservations about this particular bit of wisdom. Specifically: Is premature optimization really that dangerous, and what&#8217;s the difference between &#8220;premature optimizing&#8221; and simply building something properly the first time? <\/p>\n<p>In my professional career, I can&#8217;t remember a single instance where premature optimization caused a serious disruption. Maybe that&#8217;s a side-effect of the domain I work in. Games have very strict performance requirements that would seem completely unreasonable &#8211; bordering on fanatical &#8211; to someone working on (say) database administration. The performance of your program is continuously expressed to the user through the framerate of your full-screen application. If a thread stalls, if a frame is dropped, if texture data isn&#8217;t fetched in time, if you run out of VRAM, if you oversaturate the memory bus, or if one of a dozen or so other systems falls behind, then it will create problems that a human being can <b>see and feel<\/b>. <\/p>\n<p>Contrast this with something like a Pixar-style render farm that chugs away rendering gigantic images all day long. Both the game and the Pixar-renderer are rendering images. Time is money so there&#8217;s a huge financial incentive to get the Pixar program to run as fast as possible, but if there was a bug that wasted 15% of the available processing power, how long would it take someone to notice? Would they? Meanwhile in a game, dropped or late frames give the user a realtime visualization of your sins. It&#8217;s hard for the user to <b>not<\/b> notice performance problems.<\/p>\n<p>I&#8217;ve spent a lot of time in this domain that&#8217;s obsessed with performance and maybe a little negligent when it comes to maintaining code, and perhaps that time has blinded me to the wisdom of Knuth&#8217;s words, but what&#8217;s the actual damage of premature optimization? I get that a programmer might blow a bunch of time squeezing an extra 2% performance out of some system that ultimately doesn&#8217;t matter, but aside from the squandered programmer hours I don&#8217;t see how it hurts a project. And if we&#8217;re worried about wasted programmer hours then we have bigger fish to fry than this. Unreadable code, dependency hell, lack of documentation, failure to abide by best coding practices &#8211; all of these have devoured far more of my hours than someone&#8217;s mis-spent weekend tinkering with trivial concerns. I can believe that premature optimization is a bad thing, I just can&#8217;t get behind the notion that it poses a serious threat to our productivity. At least the premature optimizer is wasting their own time instead of mine.<\/p>\n<p><!--more--><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/stock_old_mainframe.jpg' width=100% alt='Sir, your 4Kb RAM upgrade just arrived. The forklift is bringing it up now.' title='Sir, your 4Kb RAM upgrade just arrived. The forklift is bringing it up now.'\/><\/div><div class='mouseover-alt'>Sir, your 4Kb RAM upgrade just arrived. The forklift is bringing it up now.<\/div><\/p>\n<p>I understand things were different in 1974. I didn&#8217;t do much programming back then on account of being <a href=\"?p=12698\">only three years old<\/a>. Processor cycles were literally thousands of of times more precious than they are today, and computer memory was more scarce by a factor of millions. I imagine those sorts of extreme limitations might lead the odd programmer to fritter away several hours of productivity worrying about individual bits, and maybe the practice was common enough for Knuth to name it as an &#8220;evil&#8221;, but during my career I&#8217;ve seen more productivity lost to pointless arguments over brace styles than to misguided efforts at optimization.<\/p>\n<p>But maybe I&#8217;ve been lucky. Maybe premature optimization is still a scourge industry-wide, even if it&#8217;s never afflicted any of my colleagues. Maybe I&#8217;m just oblivious to it. Maybe I&#8217;m actually a terrible offender in this regard and none of my colleagues ever had the heart to tell me. Like I said earlier, I&#8217;m not totally clear on where you&#8217;d draw the line between &#8220;optimizing&#8221; and simply &#8220;building it right the first time&#8221;.<\/p>\n<h3>Perhaps an Example Would be Useful<\/h3>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/starcraft2_tychus2.jpg' width=100% alt='I wonder if Tychus Findlay was a fan of Warhammer 40k.' title='I wonder if Tychus Findlay was a fan of Warhammer 40k.'\/><\/div><div class='mouseover-alt'>I wonder if Tychus Findlay was a fan of Warhammer 40k.<\/div><\/p>\n<p>Let&#8217;s say we&#8217;ve got a game where the level is a tidy grid of rooms. Yes, that&#8217;s a very boring design. But it&#8217;s easy to visualize and that&#8217;s what&#8217;s important for this discussion. You&#8217;ve got an N&times;N grid, where every room occupies one space on the grid. This means the whole thing can be stored in an easy-peasy 2D array. If you want to know about the room position 3&times;4, then you can just look it up like so:<\/p>\n<pre lang=\"csharp\">\r\n\/\/In c sharp...\r\nRoom r = my_rooms[3,4];\r\n\r\n\/\/In C++...\r\nRoom* r = my_rooms[3][4];\r\n\r\n<\/pre>\n<p>(Having used C sharp for a few weeks now, I have to say I prefer the CS approach to expressing array indices. [3,4] is a lot less annoying to type than [3][4], and it&#8217;s shorter by one character. And even though the C++ way is far more familiar to me, I still find the C# syntax to be more readable.)<\/p>\n<p>Whatever. Simple. We just fill the array when the program starts and then we never have to worry about it again.<\/p>\n<p>The problem with this design is that you have all the rooms in memory at once. That&#8217;s fine if the grid is small, but if this is an open-world kinda deal with miles of dungeon<span class='snote' title='1'>MILES of same-sized rooms? Now the game is starting to sound REALLY boring.<\/span> then this is going to be a huge waste. The game is probably only interested in the rooms directly surrounding the player, and if you&#8217;ve got tens of thousands of them in memory then that&#8217;s going to incur a massive cost. It will devour memory, and the loading screen will be intolerable. <\/p>\n<p>The other design you could use is to have rooms dynamically allocated as needed. Instead of creating all the rooms at startup and storing them in a tidy grid, you create them as the player gets close to them and you clear them out of memory if the player leaves the area. <\/p>\n<p>The problem is that this is a monumentally more complex design<span class='snote' title='2'>Er, it&#8217;s not actually THAT complex. But it&#8217;s complex compared to the array.<\/span>, and that complexity will have far-reaching consequences in your code.<\/p>\n<p>Now you need a background thread to load in rooms on demand, and free them up when no longer needed. Are those rooms filled with other resources like enemies, game items, or textures? Are those things used elsewhere? Can we get rid of them? We&#8217;ll need a system for tracking all of that stuff.<\/p>\n<p>The pathfinding system will need to be updated. If the pathing routine is trying to work out a route from A to B, what happens if its attempted route takes it from a loaded room to an unloaded one? Should it give up? Should it signal the room-caching thread that it needs this room and then wait for it to become available? It depends on the game.<\/p>\n<p>Physics needs to be able to handle having things vanish from the scene. An object might be on the threshold between rooms, and then one of those rooms gets unloaded as the player moves away. We need to make sure the physics engine isn&#8217;t going to freak out when this happens. If physics object A is resting on top of physics object B, but both of them belong to different rooms, then how do we handle if one of them goes missing? If B simply vanishes, then A will fall down to the floor. But then if the player returns and B reappears, A and B will both occupy the same space and the physics system will probably throw a fit over that. If you&#8217;re very lucky you won&#8217;t lose three hours trying to figure out why 1 in 100 NPCs are randomly killed by props travelling at mach 2.<\/p>\n<p><a href='https:\/\/www.wired.com\/1997\/01\/did-gates-really-say-640k-is-enough-for-anyone\/'><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/stock_memory.jpg' width=100% alt='Bill Gates never actually said that &quot;640k should be enough for anybody&quot, and if you look at the software his company designed it is pretty clear he had a slippery grip on the concept of finite memory.' title='Bill Gates never actually said that &quot;640k should be enough for anybody&quot, and if you look at the software his company designed it is pretty clear he had a slippery grip on the concept of finite memory.'\/><\/div><\/a><div class='mouseover-alt'>Bill Gates never actually said that &quot;640k should be enough for anybody&quot, and if you look at the software his company designed it is pretty clear he had a slippery grip on the concept of finite memory.<\/div><\/p>\n<p>We&#8217;ll need to synchronize these changes to the world state with the changes to the player, which might create strange, game-breaking bugs. Let&#8217;s say the player opens a treasure chest, removes the treasure, and walks away so the treasure room de-spawns. Obviously we need to save the state of the now-empty treasure room to disk, or we&#8217;ll create an exploit. But let&#8217;s say the player loots the chest, runs away, the room despawns, and then they notice their boss is approaching their cubicle so they exit the game without saving via Alt-F4<span class='snote' title='3'>Because not honoring Alt-F4 is inherently a terrible design.<\/span>. A few minutes later they launch the game. The treasure room was saved to disk, so it remains empty. But the player exited the game without saving the state of their character, so they no longer have that treasure in their inventory. The treasure has vanished forever. This may be annoying or it might be game-breaking<span class='snote' title='4'>You lost the key that exits the dungeon? Oops!<\/span>, depending on the design.<\/p>\n<p>There will be similar concerns with many of the other systems: Audio, rendering, triggers, lights, particles, and countless other systems will need to be designed in such a way that they can operate gracefully when objects appear and vanish without warning from one frame to the next. (Or they need to communicate with some sort of management system that&#8217;s in charge of loading and unloading. It&#8217;s more work either way.)<\/p>\n<p>None of these problems are insurmountable. In fact, these problems should all have straightforward solutions. The point I&#8217;m making is that this is a lot of work compared to the naive approach of tossing everything into an ever-present array. <\/p>\n<p>Note for the non-coders: From here on I&#8217;m going to refer to this other approach as using a &#8220;hashtable&#8221;. I&#8217;m not going to stop and explain what a hashtable is right now, although if you&#8217;re really curious <a href=\"https:\/\/en.wikipedia.org\/wiki\/Hash_table\">you can read about it on your own<\/a>. There are a lot of ways to store data and each of them has different strengths and drawbacks, but to keep things simple we&#8217;re just talking about two:<\/p>\n<p>1) Putting stuff into an ever-present array, which is simple but can be wasteful at higher scales.<br \/>\n2) Putting stuff into a hashtable, which is much more efficient but a lot more trouble to implement. (The hashtable itself is trivial to set up, but making all the other systems operate in a world without guaranteed data availability is non-trivial.)<\/p>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/stock_hard_drive2.jpg' width=100% alt='For optimal hard drive performance, take the cover off once a month and oil the disks. It&apos;ll keep them spinning smoothly!' title='For optimal hard drive performance, take the cover off once a month and oil the disks. It&apos;ll keep them spinning smoothly!'\/><\/div><div class='mouseover-alt'>For optimal hard drive performance, take the cover off once a month and oil the disks. It&apos;ll keep them spinning smoothly!<\/div><\/p>\n<p>The thing is, you really do want to pick one and stick with it. It&#8217;s far easier to begin with a hashtable than to get weeks into a project and then try to retrofit your design into a hashtable. Retrofitting later will mean making changes to all those other subsystems: AI, pathfinding, physics, sounds, etc. Going back to old code to make changes is far more time consuming than making new code. Once the pathfinding is working, I want to be able to treat it like a magic box and forget about it so I can spend my finite mental bandwidth on other tasks. I don&#8217;t want to have to come back three weeks later and answer the question of, &#8220;So what happens if a room vanishes from memory while I&#8217;m routing a path through it?&#8221;<\/p>\n<p>So early on in a project I&#8217;ll come to some sort of crossroads. I&#8217;ll have to choose between an array or a hashtable. I don&#8217;t want to do the extra work of implementing a hashtable if I&#8217;m not going to need it, since it will add a bit of programming overhead to every single thing I add later. On the other hand, I really don&#8217;t want to start with an array and then have to switch later. <\/p>\n<p>Gosh, it would be nice to know ahead of time if I&#8217;m going to need the hashtable. I should probably look at how many resources these rooms will take. How many can I reasonably fit into memory before I have to worry about them? How large will they be on disk? How much processing power will each of them consume per frame? How difficult is it to pull a room into memory when the game is running? I don&#8217;t need exact numbers, and in fact getting exact numbers at this stage is impossible because a lot of systems haven&#8217;t been built yet. I just need a ballpark estimate so I have basic awareness of the tradeoffs I&#8217;m dealing with.<\/p>\n<p>So I start asking these questions about memory usage and processing cost, trying to figure out what design I want to use. And inevitably another programmer will caution me against &#8220;early optimization&#8221;. &#8220;Whoa there Shamus, it&#8217;s way too early for you to be optimizing!&#8221; <\/p>\n<p>Is this really &#8220;optimization&#8221;? And is it really &#8220;early&#8221;? <\/p>\n<p>Is this how the other coders work these days? Just code under the assumption that you have infinite memory, CPU cycles, and storage space, and then re-engineer everything later once you start running to hard limits?<\/p>\n<p>I dunno. I&#8217;m sure most programmers will concede that what I&#8217;m doing here is neither early or optimization, but just basic design work. The thing is, I&#8217;ve never figured out where you&#8217;re supposed to draw the line. When do you cross the magic threshold where it&#8217;s supposedly okay to worry about CPU cycles again? When does it stop being &#8220;early&#8221;? <\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;Premature optimization is the root of all evil.&#8221; That quote by Donald Knuth gets repeated a lot in programming circles.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[66],"tags":[],"class_list":["post-42833","post","type-post","status-publish","format-standard","hentry","category-programming"],"_links":{"self":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/42833","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=42833"}],"version-history":[{"count":15,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/42833\/revisions"}],"predecessor-version":[{"id":42848,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/42833\/revisions\/42848"}],"wp:attachment":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=42833"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=42833"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=42833"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}