C++ vs C++/CX (Part 1) Testing basic structs

I have been looking into the difference between native C++ and Microsoft’s extension of C++ called C++/CX. C++/CX is similar but very much revised version of C++/CLI (along with other Microsoft variations of C++). CX sees very heavy use in their Metro C++ based apps. It looks like CX is just a compiler extension and thus you can compile normal C++ along with CX extensions. This is an extremely nice feature since you can compile cross platform code into your Windows apps. 

Before I start, I would like to point out that CX is Microsoft only. In other words, you can only compile CX code using the Visual C++ compiler. You cannot compile any CX code with any other compiler and thus the portability of your code is limited to Windows (8?) only.


 

Getting Started

First thing first; I setup a test for a stack allocated struct. I have duplicated a base struct, one in normal C++ and the other in the CX variation.

I had some issues with the CX compiler picking up the CX extensions on first go. If you get this issue, I solved it by adding

</p><p>#include "App.g.h"</p><p>

compiling and then removing it. Ok, lets keep moving.

The two structs are as follows:

</p><p>//Managed<br />ref struct myStruct sealed<br />{<br />public:<br /> myStruct(int inputInt)<br /> {<br /> //You cannot do inline initialization it looks like<br /> this-&gt;testInt = inputInt;<br /> }</p><p>property int testInt;<br />};</p><p>//Non managed<br />struct myStruct2<br />{<br />public:<br /> myStruct2(int inputInt)<br /> : testInt(inputInt)<br /> {</p><p>}</p><p>int testInt;<br />};</p><p>

I added this into it’s own header file. I’ll let you create and name it yourself. Just remember to add it in wherever you need to use the code.

ref

Ok, first I want to talk about the ref keyword. This keyword indicates that the class is part of the CX extension. It also indicates that the class is managed. Based on this it is the same as saying “class” in c#. Basically from what I understand this indicates that the class will go into the GC (garbage collector) heap. Any other examples I have seen seems to require that this keyword is added if the class belongs to the CX extension.

sealed

In my experimentation, the compiler began to demand that this keyword once I added a constructor. If I remove it, it throws a:

Error 1 error C2456: ‘myStruct’ an unsealed ref class cannot have a public visible constructor. Seal the class, or specify constructor as ‘internal’, ‘protected private’ or ‘private’ instead.

From the MSDN documentation, sealed indicates that:

sealed is a context-sensitive keyword for ref classes that indicates that a virtual member cannot be overridden, or that a type cannot be used as a base type.

This is unlike normal C++. It seems like CX requires that if you expose the constructor publicly, it is the end of the inheritance. This is similar to the final keyword introduces in the C++ 11 specification. At this current time I am not sure what this means as far as the CX implementation, but I am sure I will discover why they made this design choice shortly.

property 

This is a direct borrow from C#. A property will will create something similar to:

</p><p>int myInt { get; set; }</p><p>

in C#. Member variables cannot be public in CX, so one may use this to condense the getter/setter functions. CX seems to have strict rules about encapsulation. You can get around this by making member variables private and providing your own getter and/or setter functions.

Direct Initialization

I might be using the term incorrectly. However, in C++ you can initialize variables inside the constructor using the following method

</p><p>myStruct2(int inputInt)<br />: testInt(inputInt)</p><p>

This will initialize the variables before entering the constructor body. I was not able to do this in the CX version. Something tells me that this is because the member variable is a property. However, if I change make this into a normal variable and make it private, the direct initialization becomes possible.

</p><p>myStruct(int inputInt)<br /> : testInt(inputInt)<br /> {</p><p>}</p><p>private:<br /> int testInt;</p><p>

This calls for creating a separate accessor to your member variables as member variables cannot be public. 

Stack Allocation

Just like normal C++, you can stack allocate your structs/classes. To test, I created the following code:

</p><p>myStruct str1(1);<br /> myStruct2 str2(2);</p><p>str1.testInt = str2.testInt;</p><p>

This is completely legal with CX. I added a destructor (see Destructor) to the struct and it is in fact called when the instance goes out of scope.

Destructor

CX supports a destructor. However, it is not allowed to be public. This means that you cannot explicitly destroy objects. The destructor will be called when GC destroys the object. It is however, as mentioned before, possible to stack allocate CX objects. In this case, you can control destruction as it will be called when the owning function goes out of scope.


 

Closing Notes

It seems like CX is trying to find a middle ground between C++ and C# which is an interesting design choice. I will go as far as to say it is very likely that Microsoft is trying to appeal to both parties of programmers. However, both C++ and C# programmers will find this approach a bit frustrating. Both languages fore fill their own design approach which is not completely compatible with CX.

The biggest pitfall for C++ programmers seems to be the removal of real pointers. By putting CX objects into the GC heap, C++ programmers will find it somewhat frustrating as CX pointers represent C# references more than C/C++ pointers. The upside however, is that CX can by bypassed unless absolutely necessary.

On the other end C# programmers will have to put up with native C++ syntax and contentions. The Header/Implementation code setup is inherited from C++ (as this is still C++, not C#).

The biggest pit fall for both sides is that CX seems to have a tight syntax rule base. Neither language enforces such strict rules on public vs private elements. As someone who works in both languages, this is a bit frustrating.

DirectX: Why examples call XMMatrixTranspose

I started looking into DirectX over spring break from college and came across this little interesting issue. I noticed that the Microsoft examples were calling XMMatrixTranspose in locations such as:


cb.mWorld = XMMatrixTranspose( g_World );
cb.mView = XMMatrixTranspose( g_View );
cb.mProjection = XMMatrixTranspose( g_Projection );

which surprised me because I always assumed that DirectX is all row major as far as matrix math goes.

Turns out the GLSL shader system uses column major as a default. I am not sure were this comes from; probably somewhere from the past, but I couldn’t let it just be like that. Transposing matrixes is an unnecessary code bottleneck, so better avoid it where possible.

The simple solution is to add the following to your shader:


#pragma pack_matrix( row_major )

and your program should be able to feed the shaders row major matrixes now. This means that the above code is now:


cb.mWorld = g_World;
cb.mView = g_View;
cb.mProjection = g_Projection;

Visual Studio for Mac? MonoDevelop is your weapon

Let me first point out that I don’t like MonoDevelop; a lot of mono based projects and products like Unity still rely on the old 2.8.X version of mono which isn’t the best IDE. I have almost no experience with 3.X but from what i have heard it has become a decent IDE.

However, it is still a solid and good alternative. What is even better, is that it keeps it’s format as close as possible to Visual Studio so any project that you start in MonoDevelop can be opened and worked on in Visual Studio. I am a .NET programmer who find’s himself using a Mac from time to time. What is great is that I can run my projects on a Mac too! For instance, I can build an ASPX application on my Mac!

Mono is a .NET assembly parser; in other words, it replaces the .NET components with ones that can run on other platforms. My understanding is that it in itself is a compiler as well (correct me if I am wrong)

There are limitations to this. Mono is not a Microsoft project. Some say it is slow, some say it has a lot of bugs. In my experience it has not presented me with any issues. From what I understand it has become reliable enough that products like Unity use it to compile game scripts.

Anyways, head over to MonoDevelop and check it out!

Side Note: One reason why the Mono project is so popular is because it lets you port your applications to devices that .NET is not available without making huge changes to your code. For instance MonoGame allows you to port your game to almost any phone/platform out there!

 

Flipping a Boolean

This is a very quick post but something i see from time to time. Sometimes I run into code like this:

if (someBool == false)
{ 
      someBool = true;
} 
else
{ 
      someBool = false;
}

which works, but it looks ugly and clutters up your code. The easier way to do something like this, is to simply

someBool = !someBool;

The reason for this is simple. What is “Not false”? True. What is “Not True”. False. I am going to guess that there are some performance benefits to using this syntax but I have no research to back that up. Enjoy!

C#: Why you should avoid using partial classes

I have noticed this in my work with existing code; for some reason there are programmers out there who like using partial classes. As someone who has experienced this, let me quote myself on this:

If I have to go looking for your crap in different files, named unrelated to each other and calling stuff that is located in a different file, you are doing something wrong

As harsh as that might be, it is true; they are very confusing.

There is a good reason for why partial classes are part of Microsoft’s languages; so that they can wire your user interface items in a designer class which you can directly access, without inheritance, from your working class.. This is genius approach, but that does not mean you should make heavy use of this. Eventually you will confuse yourself. This concept is not to be confused with inheritance either, because they are completely different things. If you want to obtain the effect of broken up files, then use a system of inheritance instead. Though you will using a powerful programming element in the most useless way possible, at least it gives your fellow programmers some context to why you stuff is broken into 4 code files, representing the same class.

 

Why Every Programmer Should Try Game Development

It always astonishes me when I meet programmers who have been in the software industry for a while and have never even seen game code. In today’s software world I would assume that at some point a seasoned programmer would come across something flagged as “game code”. But that isn’t really the case. From the fellow programmers that I have met, I have found that game programming is “out there” or “something completely different”. It is as if people who are in game development are in one camp and everyone else is in some “I do programming” camp. Yet our camps are not so different from each other. Many of the people I know who do game development have worked or work at some point in disciplines such as web applications development or mobile development. So why not the other way around? Because it’s scary.

The most common application is one that mixes linear code with events. It is data processing code hooked up to an interface (not a class interface mind you) which is able to react to input coming from the interface. If you look at how mobile apps are done, most apps are done in this exact pattern. As a result a lot of programs are very straight forward; you get data from a source, you allow the user to manipulate it using the interface and then you put it back. There is no constant manipulation of data in the background. I don’t open my weather app on my phone to have it crunch numbers in the background somewhere to keep something going on the screen. It went to a web service, got the data, did something based on that data and now its waiting for my input. So why is game development scary? Because you have to run that code 60 times a second. The code is no longer about fore filling a role and stopping; it’s now about reacting appropriately to different situations at any moment during the execution of the program. You are now dealing with data driven programming which is morphing your data at an incredible rate.

Now that I have scared the shit out of my non game developer readers, I have some insight for you: its not all that difficult. Not only that, but you will have fun and your normal applications will get better. What? How? Get better… No! Says the programmer reading this article!

So how will it make my (insert type of application here) code better?

Remember back when you were in college you had to learn all the C/C++ gibberish that you have long forgotten? Well there was a reason why they taught you all that and it’s not a good thing that you a have forgotten it. Take for instance if you were a mobile developer.  You are working in a very tight space; you have maybe 200MB of heap space to play around with and the processor you are working on is slow… and working on other stuff at once. The language of choice is Java and for that reason you have long forgotten what a heap is and why it is important. Every time you ask for a new weather update from weather.com you just create a new object to hold the data, throwing out the old. Instead of saving a reference to the thing you just found in case the user re-requests it, you search the 2000 item list every time. The last few scenarios are some that I have seen multiple times looking through code examples and other people’s projects and they make my eyes bleed. But when you have a phone that runs through everything fairly quickly, who cares right? WRONG!

Game development is probably the best example of programmer training. Because your code is spinning 30-60 times a second that list search or extra allocation will go a long way to make your game unplayable. As a software engineer you cannot forget that one of your jobs is to make you code run well, regardless of the hardware. One of the biggest issues of developers today is that hardware is fast enough that heap abuse doesn’t smack them in the face every time they do something in their fancy weather app. They allocate an object, make a brand new one on next request, dispose of the old one and don’t notice the performance issue. But their user will notice. They will notice because he or she is running 20 fancy such apps and now their phone is coming to an unusable state. It’s not because it’s Android and it’s not because they installed 20 apps onto their phone; it is because the developers that we trust to provide good, solid apps have betrayed the phone architecture and forgot what a heap is.

Game developers are a bit different, at least most of us are. We cannot afford to allocate a brand new Vector3 every time we do a velocity calculation, especially in languages that down allow us to manage object deletion on our own (C#, Java). We can get away with some performance issues from time to time, but it starts biting us in the ass really quickly. I can get away with allocating a lot of ram and using up CPU cycles in bursts in a normal ASP.NET app. Most probably I wouldn’t notice any kind of issue. Someone who picks up videogame programming for the first time however, will quickly realize that it’s not possible to abuse memory allocation. Every little squeeze of RAM and CPU becomes a big deal as it allows you to do more. The faster your code, the more you can do with it. As the programmer becomes more and more comfortable with optimizing code, they should become more and more consistent. When they go back to what they normally work on, these skills will undoubtedly transfer over.

Video Game Development is All About Being Creative

It doesn’t matter if you are a programmer or an artist, the moment you step into video game development you have to be creative… very creative. Software development in general is a creative field but it’s much harder to be the “I’m going to be doing things no one is going to see” type of programmer. Unless you are working on some kind of genius memory management system or save game system, everything that you do will be in some way projected onto the screen. Gameplay programming, graphics programming, physics programming; they will all reflect on the composure of the game. And that’s awesome! Because it keeps you from forgetting that at the end of the day, you can’t and shouldn’t hide from what your application displays. Little details in the interfaces of apps make a big difference; whether something small makes it easier to use or simply makes the app look better. Videogames are the merger of the two disciplines; immersible game play (usability) and visuals. The flow of the game is determined by the two together put into one product and many applications developers can base their interface and usability designs off how videogames approach these areas.

A video game inside an everyday app?

For those of the readers in mobile app development, video games could be an amazing tool for boosting your future and existing products. There is a certain misconception that graphics and sprite driven interaction is a video game only thing; its not! I am not sure if you have noticed, but on platforms such as Android there are now backgrounds you can interact with. Many of them resemble a very basic but interesting video game. Personally I want to see this more in normal applications; a way to interact with an app using a game like approach. What if making a note is about pushing it through a small maze, possibly helping me remember what I wrote down, simply because it is now interactive? Or to get rid of calendar events, one of the ways to delete an event is to throw it into a small basket in the corner using a thumb flick? App developers always want and need to be ahead of the game (see what I did there?) and making them apps more video game like may just give some developers the edge.

Closing Notes

I would love to continue on about the benefits of making video games for all programmers, but it is also up to you, the reader to discover them too. The best way to improve your skills is to go outside the box and experiment; do something you have not done before. Whether video game development has a truly profound effect or makes not difference to you, it is for you to decide. However, try it out, it won’t hurt! To close off and point you in a few directions to begin with, check out the following game engines:

XNA (MonoGame)

Unity

Construct2

and begin poking around!

C# Software Architecture: Delegates

There are times, and I hope more often than not, that you have to write code which will be reused for multiple projects. Writing code in a reusable style is probably the most useful approach which leads to faster project development and reduced maintenance time. As your “reusable” code becomes more commonly implemented by you and your colleagues, it will change, morph and hopefully become faster and more reliable. There are multiple ways to approach reusable code; the most common ways are to create a library or an architecture. Both approaches are very powerful and almost always used together. In today’s blog post I am going to approach reusable code from a library stand point and then discuss how delegates make architectures powerful.

What is an architecture? To be more clear, in the case that the term is a bit vague, I am going to take a moment to explain what I define an “Architecture” as. An architecture is a set of libraries and classes which force the programmer to conform to a specific structure and implementation. Hence the word “architecture”, which is unlike a  “library” that supports your own code structure. For instance in XNA, your scene must inherit from the Game class. This is unlike a library which leaves the implementation up to you and acts more of a “tool kit” to your own code structure.

Ok good, now that I have all boring terminology clarifications out of the way, I can get into the fun stuff! In C# and many other languages, we are provided with a very powerful tool called the Delegate. This is included in some form in almost any language that supports reflection, though the implementation might not be so straight forward (has to be done through an interface in Java). If I was to describe this off the top of my head, a Delegate is a type which holds the definition (more accurately the signature) of a function. As a result it is used to hold a reference to a function which allows you to invoke it as a variable. To refer to the MSDN documentation:

delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value[…]

This means that using this, I can pass in a function as a variable into another function. For instance, if I have a function that computes the rotation of a car wheel in relation to speed, we are met with a problem; do we use miles or kilometers? A customer in the US would need this to be done in miles while a customer in Russia will need this to be done in kilometers. You are now faced with a software architecture problem; do you simply create two functions for each case? What happens if for instance, if someone needs to take my code three years from now and implement some third type of measurement? As stupidly simple as this architecture problem maybe, there are issues very similar to this that require this kind of attention. You don’t want someone ripping your code apart in the future because that fragments code versions. You don’t want every implementer to make changes to your “reusable” stuff because that well, defeats the purpose of writing reusable code.

Lets pick up the pace a little bit with some examples. I’m going to take the example I just threw at you above and show you how to implement it. Lets define the delegate first:


/// <summary>
 /// Used to compute the distance traveled per rotation of the wheel
 /// </summary>
 /// <param name="wheelSize">Size of the wheel is in inches, it is the length of one rotation</param>
 /// <returns></returns>
delegate float ComputeRotation(float wheelSize);

So in the above code, we define the “blueprint” for the function that is used in our architecture for computing the distance per rotation of the wheel. The architecture will feed the size of the wheel into your function and let you decide what the proportion is to your mile or kilometer. I made it easier where our architecture already knows the length of the wheel rather than the radius; lets not do too much math here! So now that we have the “model” for our function we can now create it. In using the delegate, we “agree” that our function will take a float for the wheel size and return a float. Everything else is up to us. Lets define a new function!


protected float computeInKM(float wheelSize)
 {
float wheelSizeInCM = wheelSize * 2.54f; //Lets convert this to cm to make it easier
return wheelSizeInCM / 100; //Return the KM value since we are still in CM
 }

I could of just returned the entire thing in the return statement but I decided break it down a little bit. So, this is our function for computing the distance a wheel has traveled in a single rotation in kilometers. Our architecture, which needs to compute the distance a car has traveled based on how many times the wheel has rotated (I would assume this is how cars do this computation). We are all set to provide our architecture a computing function! To link the code all together, since right now we just have a function and a delegate that do nothing, we can do the following:


namespace blogExamples
{
      /// <summary>
      /// Used to compute the distance traveled per rotation of the wheel
      /// </summary>
      /// <param name="wheelSize">Size of the wheel is in inches, it is the length of one rotation</param>
      /// <returns></returns>
      delegate float ComputeRotation(float wheelSize);
      class delegateExample
      {
           protected ComputeRotation rotationCompFunction;
           public delegateExample()
           {
                rotationCompFunction = computeInKM;
           }

           protected float computeInKM(float wheelSize)
           {
                float wheelSizeInCM = wheelSize * 2.54f; //Lets convert this to cm to make it easier
                return wheelSizeInCM / 100; //Return the KM value since we are still in CM
           }
     }
}

Apologies for the ever growing code. The above code you can just copy paste; it is a stand alone class that we can just create a new instance of for the sake of the example. So far this does not resemble anything “architecture” like, but it works very well for an example. I have taken the delegate out of the class and into the name space. I have found in my own experience this makes more sense since you want to reuse your delegates! Now we have literally in a way a “pointer” to our function. Now the class knows which function it can use to compute distance, we are all setup and ready to go! I am going to morph this class a few times to show you how this would look like if I just wrote the code inline in the class and then I am going to take the computeInKM out of the class, put it into my main and show you, just how powerful delegates are!  Lets get the ball rolling!


namespace blogExamples
{
       /// <summary>
       /// Used to compute the distance traveled per rotation of the wheel
       /// </summary>
       /// <param name="wheelSize">Size of the wheel is in inches, it is the length of one rotation</param>
       /// <returns></returns>
       delegate float ComputeRotation(float wheelSize);
       class delegateExample
       {
            const float sizeOfWheel = 20; //I have no idea what an actual length of a wheel is
            protected ComputeRotation rotationCompFunction; //Lets create a delegate reference
            public delegateExample()
            {
                 rotationCompFunction = computeInKM;
            }

            protected float computeInKM(float wheelSize)
            {
                 float wheelSizeInCM = wheelSize * 2.54f; //Lets convert this to cm to make it easier
                 return wheelSizeInCM / 1000; //Return the KM value since we are still in CM
            }

            public float totalDistanceTraveled(float wheelRotations)
            {
                  return wheelRotations * rotationCompFunction(sizeOfWheel);
        }
 }

This is now our class that uses an internal delegate to make our computation in KM. To call it from your main, you can simply:


class Program
 {
      static void Main(string[] args)
      {
           delegateExample exampleClass = new delegateExample();
           Console.WriteLine(exampleClass.totalDistanceTraveled(100));
           Console.ReadLine();//Stop it from closing
      }
 }

Seems simple right? But why in the world would we use a delegate? Can’t we just call the KM function and even better, just pass in what computation we want into the constructor as an enum? Well those are the better options if we setup our code this way; a delegate here, nested inside a class, inaccessible from the outside is useless. But I had to start demonstrating the idea somehow right? Now let me show you the REAL potential of a delegate. I am going to take function we loaded into our delegate OUT of the class and put it into our main “program” class. Then I am going to have my class obtain the function through it constructor. Get ready! Here we go!


namespace blogExamples
{
         /// <summary>
         /// Used to compute the distance traveled per rotation of the wheel
         /// </summary>
         /// <param name="wheelSize">Size of the wheel is in inches, it is the length of one rotation</param>
         /// <returns></returns>
         delegate float ComputeRotation(float wheelSize);
         class delegateExample
         {
               const float sizeOfWheel = 20; //I have no idea what an actual length of a wheel is
               protected ComputeRotation rotationCompFunction; //Lets create a delegate reference
               public delegateExample(ComputeRotation computationDelegate)
               {
                     rotationCompFunction = computationDelegate;
               }

               public float totalDistanceTraveled(float wheelRotations)
               {
                     return wheelRotations * rotationCompFunction(sizeOfWheel);
        }
    }
}

To the programmers reading this who are not as experienced ill run through the changes really quick (yea, I had to read stuff like this starting out too, I know the AND THEN MAGIC HAPPENS is really frustrating!). I took my function, the computeInKM and moved it (look at the up coming code, I put it into the Program class). I then modified the constructor to take a ComputeRotation delegate and assigned it to the default computation function (rotationCompFunction) variable. Lets take a look at the “Program” class now:


namespace blogExamples
{
       class Program
       {
             static void Main(string[] args)
             {
                  delegateExample exampleClass = new delegateExample(new ComputeRotation(computeInKM));
                  Console.WriteLine(exampleClass.totalDistanceTraveled(100));
                  Console.ReadLine();//Stop it from closing
             }
             protected static float computeInKM(float wheelSize)
             {
                  float wheelSizeInCM = wheelSize * 2.54f; //Lets convert this to cm to make it easier
                  return wheelSizeInCM / 1000; //Return the KM value since we are still in CM
             }
      }
}

As you can see now, my function is now in a completely difference scope and yet it is being used to compute! I hope at this point you are a starting to see the potential of this approach! In order to pass in a delegate, you you need to create a new instance of one and assign your function into it, hens why I am passing in:


       new ComputeRotation(computeInKM)

into the constructor. Exciting isn’t it?

What in the world does this have to do with software architecture?

In another blog post, I will describe how to take this concept even further with events, but delegates are still extremely important for software architecture. The examples I used represent a library more than an architecture. However, lets discuss an example (I promise, no more code!)

The big downside of using some kind of architecture is that you can’t do much about the internal workings of the architecture. This means a few things:

  • Architectures that are not flexible end up being less reusable and more specific to a certain project
  • When you want to do something your own way, well… you can’t change the internal working

Lets go back to our distance measuring example. Cars models are often built for more than one country and very often different countries have different standards. I am not an expert at car regulations but I can say for sure that in the US they use miles and in Russia they use kilometers. This creates an issue for software developers (now that we are in the modern age) because the entire digital dashboard, including GPS is affected by this. A mile is over one and a half times the distance of a kilometer and when I am in Russia, I really wouldn’t like that my GPS computes everything wrong. But this is a serious problem for developers because well, what if I wrote the architecture for the car displays ONLY in miles (well, lets assume its in C# which it most definitely isn’t)? Then that software has to be redone or they have to pay me oodles of money (Yay?) to go in and create SEPARATE version for them that does everything in kilometers. As rich as I want to be, it means I didn’t do my job right and I did not allow them to just go in and with a few lines of code change the behavior of my amazing architecture. So what do I do?

A little detour into architecture approaches; an architecture often requires that you create a class that inherits one that the engine provides (usually you can choose from multiple on what your creating). This way my architecture can take care of a lot of functionality and setup that you don’t have to. Back to the implantation world;  this means that I can define a function looped through a delegate which you can then overwrite with your own function! This is also often done through overriding, but in our case we might have a user that wants to switch between measurement types; simply changing our the delegate function will do the trick where overriding would make this more difficult.

Closing Notes

One question that you might ask, is why not simply at least for this example convert miles/km directly? Why do I need this complex setup? Well, the purpose of this article is not how to handle converting measurements, but why delegates are powerful tools. But this question raises a good point, why not simply compute in one measuring system and convert into another? Wouldn’t that be easier? Well, it’s more straight forward, but from an software standpoint it is very wasteful. On a standard computer, we really don’t care about those things because it takes so little processing power. In a car this is a big deal because well, the tech inside is simply not very powerful. As you design more and more advanced systems for a car, you have to keep in mind that your software is constantly running the calculations of distance traveled, current speed and even how far is the car behind you. The faster the refresh rate the more reliable the reading are and in many cases, the safer your car is. If someone is getting too close to me from behind, it might be too late to notify me at a refresh rate of 3 times a second that “Hey, that car is dangerously close”. This means that you really need to tighten your computation to make it finish one loop through and start the next. What do we do about this? Simple, don’t do redundant computation if you can do it right away.