Part 4 – Efficient use of variables.
This is the final part of the blog discussing how bad code does often lead to bad performance of web pages, and what bad coding habits can contribute to the slow performance. In previous parts, I’ve discussed how a lack of parallelism in code, over-reliance on server-side code, and poorly structured database queries can slow performance down.
In this final part of the blog, I shall be looking at how use of variables can contribute to bad performance. Yet again, I shall be referring to and commentating on C# examples.
Use of variables
Believe it or not, the use of variables can also impact performance!
Let’s take a simple string variable. If we have a string variable where large amounts of text will be constantly added to it, the variable will have a fair portion of memory resource allocated to it. This is because string variables are immutable – they cannot be changed once created; so when we modify a string variable, a new string instance is created on top of the old instance. Using a StringBuilder instead of string variables uses considerably less memory resource. A StringBuilder is a buffer of characters that can be changed without creating new instances each time a change is made.
Admittedly, variables will have a smaller effect on performance in comparison to other habits discussed in this series of blogs, and may only improve performance by a matter by milliseconds, or even nanoseconds. However, considering that 2 seconds is the threshold between customers being patient on a page and becoming impatient, every milli- (or nano-) second counts!
There are undoubtedly many other different coding habits that don’t deliver the desired and/or required performance. Knowing how to spot code optimisation opportunities, evaluating if the code needs to be optimised, and then actually how to optimise the code to meet one’s requirements takes time and practice. However, the sooner these habits are identified and rectified, the more likely it is that your site can keep your customers happy.
(Source: https://community.semrush.com/uploads/media/25/33/2533f309261402561981514398e61325.jpg)