{"id":42796,"date":"2018-05-22T06:00:11","date_gmt":"2018-05-22T10:00:11","guid":{"rendered":"http:\/\/shamusyoung.com\/twentysidedtale\/?p=42796"},"modified":"2018-05-22T09:03:01","modified_gmt":"2018-05-22T13:03:01","slug":"unity-week-7-why-would-you-want-to-do-that","status":"publish","type":"post","link":"https:\/\/www.shamusyoung.com\/twentysidedtale\/?p=42796","title":{"rendered":"Unity Week #7: Why Would You Want to do That?"},"content":{"rendered":"<p>&#8220;Huh. I&#8217;m keeping an awful lot of these widget objects in memory. I need them while generating the scene, and I occasionally need them later, but once the game is running they&#8217;re mostly just taking up memory. I wonder if it would be better to keep them around all the time, or throw them away once I&#8217;m done making the scene and re-create them if they&#8217;re needed later?&#8221;<\/p>\n<p>Let&#8217;s assume, for the sake of argument, that these objects have a non-trivial size and also require a non-trivial bit of processing power to create. We create lots of them, we use most of them at startup, and then as the program runs we occasionally need a few of them. (But we can&#8217;t predict which ones ahead of time.)<\/p>\n<p>This is a classic memory vs. CPU performance problem. If we had infinite memory, then there would never be a reason to get rid of these temporary objects. If we had infinite processing power and could re-create the objects for free, then there would be no reason to keep them around. But in this universe both of these resources are finite, so we need to study the problem to know what the right thing to do is.<\/p>\n<p>So I&#8217;m writing a program in C# and I need to know how big something is in memory. In C++ I would just call <code>sizeof (thing)<\/code> and it would tell me how many bytes of memory <code>thing<\/code> is using<span class='snote' title='1'>Yes, you have to make sure you&#8217;re getting the size of things and not pointers, which means you might need to step down through the object hierarchy. The point is, this is easy to do.<\/span>. This is a trivial operation, which means in C# it&#8217;s probably going to be a monumental pain in the ass. I do the usual Google search and as I feared I&#8217;m dropped directly into forum hell:<\/p>\n<p><!--more-->&#8220;You don&#8217;t need to know that.&#8221;<\/p>\n<p>&#8220;Why would you want to do that?&#8221;<\/p>\n<p>&#8220;That&#8217;s not possible in C#, and if you&#8217;re asking this question it means you&#8217;re doing something wrong.&#8221;<\/p>\n<p>Here&#8217;s my favorite:<\/p>\n<blockquote><p>Short answer:<br \/>\nYou dont.<br \/>\nLong answer:<br \/>\nYou can only do that if you type has a fixed layout and has no managed members. Structs are fixed by default. Classes can attributed to have a fixed layout.<br \/>\n(I am not showing how, as you really do not need it. It is only important when doing interop.)<\/p><\/blockquote>\n<p><i>Sure, *I* know how to do it, but I&#8217;m not going to show you because you&#8217;re a lame scrub and you don&#8217;t deserve my wisdom.<\/i><\/p>\n<p>Here&#8217;s another:<\/p>\n<blockquote><p>You may have a conceptual problem here &#8211; the size of that class is not really supposed to be exposed to you, the developer in this case.<\/p>\n<p>The underlying mechanisms used to store it are compiler details &#8211; also the compiler is optimising &#8211; which means that it is perfectly at liberty to change the sizes of certain objects if it provides a performance upgrade.<br \/>\n[&#8230;]<br \/>\nSizes of classes is a C++ concept, and even then is flaky &#8211; sizeof() in C++ can also measure the size of the virtual function table pointer IF the compiler in question implements one in a specific way.<\/p>\n<p>If you really need to know more about the size of this object internally, can you let us know why? This may make things clearer :)<\/p><\/blockquote>\n<p>Absurd dogma. &#8220;You can&#8217;t have perfect knowledge of memory usage so therefore <i>any<\/i> attempt to know about memory usage is a waste of time.&#8221; <\/p>\n<p>My contempt for these sorts of people is boundless. I&#8217;m sorry, forum idiots, but we live in a universe of finite resources and so sometimes we need to ask important questions like, &#8220;How many resources do we have?&#8221; and &#8220;Can we afford to use more?&#8221; If you&#8217;re going to reply to questions, then at the bare minimum you should <b>answer the question<\/b>. If you don&#8217;t know the answer, then don&#8217;t post. Please stop polluting the search results with your arrogance and stupidity.<\/p>\n<p>It turns out <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/5s4920fa(v=vs.110).aspx\">it is supposedly possible to get the size of something in memory<\/a>. It&#8217;s just needlessly convoluted. I find those pages in the docs and try it out. When I run my program it throws an exception:<\/p>\n<p><code>ArgumentException: Type Widget cannot be marshaled as an unmanaged structure.<\/code><\/p>\n<p>Searching for an explanation of what I&#8217;m doing wrong just sends me back into the nest of morons asking &#8220;Why would you do that?&#8221;, and I&#8217;ve read enough of their nonsense for one day. <\/p>\n<p>So I give up and just do it manually. I look at each variable in my class:<\/p>\n<pre lang=\"csharp\" line=\"1\">\r\npublic class SpaceMarine : Meathead\r\n{\r\n  string name;\r\n  string profane_nickname;\r\n  const bool is_dude = true;\r\n  float beard_stubble;\r\n  double burlyness;\r\n  int bullets;\r\n  int genades;\r\n  int hitpoints;\r\n  int armor;\r\n  long aliens_killed_with_firearms;\r\n  long aliens_killed_with_melee_weapons;\r\n  long aliens_killed_with_bare_hands;\r\n  long aliens_killed_with_shouting;\r\n  int dead_wives;\r\n  bool cigar;\r\n};<\/pre>\n<p>Then I look up all the type of each variable to get the size, just in case it&#8217;s different from what I&#8217;m used to in C++. Then I use my primate hands to type these numeric values into a calculator so I can know what the total is. And the whole time I&#8217;m gritting my teeth at this completely stupid task because this is exactly the sort of dumb busywork we invented computers for. And the only reason I can&#8217;t use a computer to solve this problem is that the language I&#8217;m using is trying to help me to death. <\/p>\n<p>Okay, so I add up all the values. The above example<span class='snote' title='2'>Which I made up for the purposes of demonstration.<\/span> comes to 61 bytes, plus whatever space the name \/ nickname strings take up.  That&#8217;s trivial, and I could safely keep a few thousand of these around without worrying about memory overhead.<\/p>\n<p>Yes, this SpaceMarine example is small and simple enough that your average coder could probably glance at the definition and eyeball it. They can take a guess at the memory usage and get within a factor of 2 without needing to whip out the calculator. But in practice your data structures will be more complex than this, with classes containing other classes. The SpaceMarine might contain a WeaponClass which contains a WeaponModel which contains a WeaponMod which contains a Damage type, and it&#8217;s pretty reasonable to not want to have to scan through thirty variables across five different source files before you know how big something is. In a less obstructionist language I could get this information in a line or two of code, and here it turns into to a little bit of middle school math homework.<\/p>\n<p>Note that I&#8217;m not even trying to <b>do<\/b> anything with this information in my program. It&#8217;s not like I&#8217;m asking C# for direct memory access or anything &#8220;crazy&#8221; like that. For the most part I applaud C# and its attempts to save the programmer from having to <b>do things<\/b>, but the moment the language attempts to save you from <b>knowing things<\/b> then something has gone horribly wrong.<\/p>\n<h3>On The Other Hand&#8230;<\/h3>\n<p>Despite my griping, I&#8217;m really warming up to Unity \/ C#. For every annoyance it puts on me, it relieves a couple of longstanding C++ headaches. It&#8217;s great being able to write code without needing to juggle stupid header files. It&#8217;s a massive relief to get a project rolling without messing around with libraries and include paths. And for the 90% of the project where I don&#8217;t care about memory usage, it&#8217;s really nice to not have to worry about memory usage.<\/p>\n<p>It&#8217;s great having a platform with more stuff built-in, because it makes everything else more modular. I mean, this is what it&#8217;s like in C++:<\/p>\n<p>&#8220;I&#8217;d like to add a console window to this project. Just something simple to draw scrolling text on screen. No problem, I wrote one of those last year. Oh, but that code uses my 3D vectors to draw the window. Ok, I&#8217;ll include those vectors. But that code is tied to the 4&#215;4 matrix code because those two types interact. That 4&#215;4 Matrix code references my camera framework, the camera framework depends on my RGB color code, and the RGB color code uses my string parser for turning HTML-style #RRGGBB strings into color values.&#8221;<\/p>\n<p>All I wanted was to draw some rectangles on screen and now I&#8217;m importing 5,000 lines of code. <\/p>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/pixelcity2_knot.jpg' width=100% alt='Little knot here.' title='Little knot here.'\/><\/div><div class='mouseover-alt'>Little knot here.<\/div><\/p>\n<p>You can try to make your stuff as self-contained as possible, but that&#8217;s pretty hard to do when you&#8217;re writing code for basic building blocks that get used everywhere. <\/p>\n<p>In Unity, all of that crap comes built-in and you don&#8217;t have to go on some <a href=\"?p=9557\">crazy misadventure through dependency hell<\/a>. Everything &#8220;just works&#8221;. It&#8217;s amazing and it makes programming fun again. Or at least, it&#8217;s fun when I don&#8217;t have to go dumpster diving in internet forums for answers.<\/p>\n<p>Next week I&#8217;ll talk about a couple of hard jobs that Unity made easy.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;Huh. I&#8217;m keeping an awful lot of these widget objects in memory. I need them while generating the scene, and I occasionally need them later, but once the game is running they&#8217;re mostly just taking up memory. I wonder if it would be better to keep them around all the time, or throw them away [&hellip;]<\/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-42796","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\/42796","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=42796"}],"version-history":[{"count":7,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/42796\/revisions"}],"predecessor-version":[{"id":42803,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/42796\/revisions\/42803"}],"wp:attachment":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=42796"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=42796"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=42796"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}