title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
2:138 | |
2:139 | Figure 2.15: GitHub Actions tab |
2:140 | Here, we described two ways to deploy a web app. In Chapter 8, Understanding DevOps Principles and CI/CD, we will go further into Continuous Integration/Continuous Delivery (CI/CD) strategies to guarantee all the steps required to get an application to production, that is, building, testing, deployment to staging, and deployment to production. |
2:141 | Now that you have learned a great way to make your web apps run on Azure, using Visual Studio as a helpful tool, it is essential to understand some performance issues that may cause struggles while creating a solution. |
2:142 | Performance issues that need to be considered when programming in C# |
2:143 | Nowadays, C# is one of the most used programming languages in the world, so awareness of C# programming best practices is fundamental for the design of good architectures that satisfy the most common non-functional requirements. |
2:144 | The following sections mention a few simple but effective tips – the associated code samples are available in this book’s GitHub repository. It is worth mentioning that .NET Foundation has developed a library dedicated to benchmarking called BenchmarkDotNet. You may find it useful for your scenarios. Check it out at https://benchmarkdotnet.org/. |
2:145 | String concatenation |
2:146 | This is a classic one! A naive concatenation of strings with the + string operator may cause serious performance issues since every time two strings are concatenated; their contents are copied into a new string. |
2:147 | So, if we concatenate, for instance, 10 strings that have an average length of 100, the first operation has a cost of 200, the second one has a cost of 200+100=300, the third one has a cost of 300+100=400, and so on. It is not difficult to convince yourself that the overall cost grows as m*n2, where n is the number of strings and m is their average length. n2 is not too big for small n (say, n < 10), but it becomes quite big when n reaches the magnitude of 100-1,000 and is unacceptable for magnitudes of 10,000-100,000. |
2:148 | Let us look at this with some test code that compares naive concatenation with the same operation but performed with the help of the StringBuilder class (the code is available in this book’s GitHub repository): |
2:149 | |
2:150 | Figure 2.16: Concatenation test code result |
2:151 | If you create a StringBuilder class with something like var sb = new System.Text.StringBuilder(), and then you add each string to it with sb.Append(currString), the strings are not copied; instead, their pointers are queued in a list. They are copied in the final string just once when you call sb.ToString() to get the final result. Accordingly, the cost of StringBuilder-based concatenation grows simply as m*n. |
2:152 | Of course, you will probably never find a piece of software with a function like the preceding one that concatenates 100,000 strings. However, you need to recognize pieces of code like these where the concatenation of some 20-100 strings, say, in a web server that handles several requests simultaneously might cause bottlenecks that damage your non-functional requirements for performance. |
2:153 | Exceptions |
2:154 | Always remember that exceptions are much slower than normal code flow! So, the usage of try-catch needs to be concise and essential; otherwise, you will have big performance issues. |
2:155 | The following two samples compare the usage of try-catch and Int32.TryParse to check whether a string can be converted into an integer, as follows: |
2:156 | private static string ParseIntWithTryParse() |
2:157 | { |
2:158 | string result = string.Empty; |
2:159 | if (int.TryParse(result, out var value)) |
2:160 | result = value.ToString(); |
2:161 | else |
2:162 | result = `There is no int value`; |
2:163 | return $`Final result: {result}`; |
2:164 | } |
2:165 | private static string ParseIntWithException() |
2:166 | { |
2:167 | string result = string.Empty; |
2:168 | try |
2:169 | { |
2:170 | result = Convert.ToInt32(result).ToString(); |
2:171 | } |
2:172 | catch (Exception) |
2:173 | { |
2:174 | result = `There is no int value`; |
2:175 | } |
2:176 | return $`Final result: {result}`; |
2:177 | } |
2:178 | |
2:179 | The second function does not look dangerous, but it is thousands of times slower than the first one: |
2:180 | |
2:181 | Figure 2.17: Exception test code result |
2:182 | To sum this up, exceptions must be used to deal with exceptional cases that break the normal flow of control, for instance, situations when operations must be aborted for some unexpected reasons, and control must be returned several levels up in the call stack. |
2:183 | Multithreading environments for better results – dos and don’ts |
2:184 | If you want to take advantage of all the hardware that the system you are building provides, you must use multithreading. This way, when a thread is waiting for an operation to complete, the application can leave the CPU to other threads instead of wasting CPU time. |
2:185 | On the other hand, no matter how hard Microsoft works to help with this, parallel code is not as simple as eating a piece of cake: it is error-prone and difficult to test and debug. The most important thing to remember as a software architect when you start considering using threads is does your system require them? Non-functional and some functional requirements will answer this question for you. |
2:186 | As soon as you are sure that you need a multithreading system, you should decide on which technology is more adequate. There are a few options here, as follows: |
2:187 | |
2:188 | Creating an instance of System.Threading.Thread: This is a classic way of creating threads in C#. The entire thread life cycle will be in your hands. This is good when you are sure about what you are going to do, but you need to worry about every single detail of the implementation. The resulting code is hard to conceive and debug/test/maintain. So, to keep development costs acceptable, this approach should be confined to a few fundamental, performance-critical modules. |
2:189 | Managing threads using System.Threading.ThreadPool: You can reduce the complexity of this implementation by using the ThreadPool class. Especially if you intend to develop a solution in which you will have many threads being executed, this could be a good option. It is worth mentioning that the .NET thread pool has been re-implemented in .NET 6 as a C# class, which will bring new possibilities for experimentation or customization. |
2:190 | Programming using System.Threading.Tasks.Parallel classes: Since .NET Framework 4.0, you can use parallel classes to enable threads in a simpler way. This is good because you do not need to worry about the life cycle of the threads you create, but it will give you less control over what is happening in each thread. |
2:191 | Developing using asynchronous programming: This is, for sure, the easiest way to develop multithreaded applications since the compiler takes on most of the work. Depending on the way you call an asynchronous method, you may have the Task created running in parallel with the Thread that was used to call it or even keep that Thread waiting without suspending for the Task that was created to conclude. This way, asynchronous code mimics the behavior of classical synchronous code while keeping most of the performance advantages of general parallel programming: |
2:192 | The overall behavior is deterministic and does not depend on the time taken by each task to complete, so non-reproducible bugs are less likely to happen, and the resulting code is easy to test/debug/maintain. Defining a method as an asynchronous task or not is the only choice left to the programmer; everything else is automatically handled by the runtime. The only thing you should be concerned about is which methods should have asynchronous behavior. It is worth mentioning that defining a method as async does not mean it will execute on a separate thread. You may find useful information in a great sample at https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/. |
2:193 | Later in this book, we will provide some simple examples of asynchronous programming. For more information about asynchronous programming and its related patterns, please check out Task-Based Asynchronous Patterns in the Microsoft documentation (https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap). |
2:194 | |
2:195 | TAP is the evolution of EAP (Event-Based Asynchronous Pattern), which, in turn, is the successor to APM (Asynchronous Programming Model Pattern). |
2:196 | |
2:197 | |
2:198 | |
2:199 | |
2:200 | No matter the option you choose, there are some dos and don’ts that, as a software architect, you must pay attention to. These are as follows: |
2:201 | |
2:202 | Do use concurrent collections (System.Collections.Concurrent): As soon as you start a multithreading application, you have to use these collections. The reason for this is that your program will probably manage the same list, dictionary, and so on from different threads. The use of concurrent collections is the most convenient option for developing thread-safe programs. |
2:203 | Do worry about static variables: It is not possible to say that static variables are prohibited in multithreading development, but you should pay attention to them. Again, multiple threads taking care of the same variable can cause a lot of trouble. If you decorate a static variable with the [ThreadStatic] attribute, each thread will see a different copy of that variable, hence solving the problem of several threads competing on the same value. However, ThreadStatic variables cannot be used for extra-thread communications since values written by a thread cannot be read by other threads. In asynchronous programming, AsyncLocal<T> is the option for doing something like that. |
2:204 | Do test system performance after multithreading implementations: Threads give you the ability to take full advantage of your hardware, but in some cases, badly written threads can waste CPU time just doing nothing! Similar situations may result in almost 100% CPU usage and unacceptable system slowdowns. In some cases, the problem can be mitigated or solved by adding a simple Thread.Sleep(1) call in the main loop of some threads to prevent them from wasting too much CPU time, but you need to test this. A use case for this implementation is a Windows service with many threads running in the background. |
2:205 | Do not consider multithreading easy: Multithreading is not as simple as it seems in some syntax implementations. While writing a multithreading application, you should consider things such as the synchronization of the user interface, threading termination, and coordination. In many cases, programs just stop working well due to bad implementation of multithreading. |
2:206 | Do not forget to plan the number of threads your system should have: This is especially important for 32-bit programs. There is a limitation regarding how many threads you can have in any environment. You should consider this when you are designing your system. |
2:207 | Do not forget to end your threads: If you do not have the correct termination procedure for each thread, you will probably have trouble with memory and handling leaks. |
2:208 | |
2:209 | Scalability, performance tips, and multithreading are the main tools we can use to tune machine performance. However, the effectiveness of the system you design depends on the overall performance of the entire processing pipeline, which includes both humans and machines. For this reason, in the next section, we will discuss how to design effective user interfaces. |
2:210 | Software usability: how to design effective user interfaces |
2:211 | As a software architect, you cannot improve the performance of humans, but you can improve the performance of human-machine interaction by designing an effective user interface (UI), that is, a UI that ensures fast interaction with humans, which, in turn, means the following: |
2:212 | |
2:213 | The UI must be easy to learn to reduce the time that is needed for the target users to learn how to operate it. This constraint is fundamental if UI changes are frequent and for public websites that need to attract the greatest possible number of users. |
2:214 | The UI must not cause any kind of slowdown in data insertion; data entry speed must be limited only by the user’s ability to type, not by system delays or additional gestures that could be avoided. |
2:215 | Today, we must also consider the accessibility aspects of our solutions since doing so allows us to include more users. |
2:216 | |
2:217 | It is worth mentioning that we have UX experts in the market. As a software architect, you must decide when they are essential to the success of the project. The following are a few simple tips when it comes to designing easy-to-learn user interfaces: |
2:218 | |
2:219 | Each input screen must state its purpose clearly. |
2:220 | Use the language of the user, not the language of developers. |
2:221 | Avoid complications. Design the UI with the average case in mind; more complicated cases can be handled with extra inputs that appear only when needed. Split complex screens into more input steps. |
2:222 | Use past inputs to understand user intentions and to put users on the right path with messages and automatic UI changes, for instance, cascading drop-down menus. |
2:223 | Error messages are not bad notes that the system gives to the users who do something that’s wrong, but they must explain how to insert the correct input. |
2:224 | |
2:225 | Fast UIs result from efficacious solutions to the following three requirements: |
2:226 | |
2:227 | Input fields must be placed in the order they are usually filled, and it should be possible to move to the next input with the Tab or Enter key. Moreover, fields that often remain empty should be placed at the bottom of the form. Simply put, the usage of the mouse while filling in a form should be minimized. This way, the number of user gestures is kept to a minimum. In a web application, once the optimal placement of input fields has been decided, it is enough to use the tabindex attribute to define the right way for users to move from one input field to the next with the Tab key. |
2:228 | System reactions to user input must be as fast as possible. Error messages (or information ones) must appear as soon as the user leaves the input field. The simplest way to achieve this is to move most of the help and input validation logic to the client side so that system reactions do not need to pass through both communication lines and servers. |
2:229 | Efficacious selection logic: Selecting an existing item should be as easy as possible; for example, selecting one out of some thousands of products in an offer must be possible with a few gestures and with no need to remember the exact product name or its barcode. The next subsection analyzes techniques we can use to decrease complexity to achieve fast selection. |
2:230 | |
2:231 | In Chapter 19, Client Frameworks: Blazor, we will discuss how this Microsoft technology can help us with the challenges of building web-based applications with C# code in the frontend. |
2:232 | Designing fast selection logic |
2:233 | When all possible choices are in the order of magnitude of 1-50, the usual drop-down menu is enough. For instance, take this currency selection drop-down menu: |
2:234 | |
2:235 | Figure 2.18: Simple drop-down menu |
2:236 | When the order of magnitude is higher but less than a few thousand, an autocomplete that shows the names of all the items that start with the characters typed by the user is usually a good choice: |
2:237 |