Search

Xamarin Profiler and Memory Management

App memory management has become one of the key priorities for any developer today. With new-gen energy-efficient processors launching every day &  operating systems shifting towards efficient power usage along with sleek UI experience, today’s developers face a challenge of developing apps that are sleek & efficient in memory management along with an intelligent tool to check memory leakage proactively. In this article, I will be covering two major topics i.e. xamarin profiler (Part 1) and memory management (Part 2). Part 1: Xamarin Profiler Introduction to Xamarin Profiler: Xamarin Profiler is a tool developed by Microsoft that helps the developers to analyze the app's behavior, and its memory allocations with the help of a visual studio. It is a graphical interface that supports doing profiling in android, ios, tvos, mac applications in mac and android, ios, tvos applications in windows.  Why use a profiler: We all know that sometimes we don't properly dispose of the objects and therefore the garbage collector will not collect them and remove them from the memory.   In other words, with the help of the profiler, we can check memory leaks that are being held by objects which should ideally be disposed of.  Before that, let's understand how the operating system manages the memory. There are two types of memory, native memory and managed memory. All the ios and android related objects like views, example buttons, text views fall into the native memory and the dot net-related objects, for example, subscriptions, event handlers, threads go into managed memory. Whenever there is a process, the operating system gives a small piece of this memory chunk to xamarin mono. So in order to check the memory allocations of managed memory, we need a profiler.  Garbage Collector: Before getting started with the profiler, let's understand what a garbage collector is. The garbage collector collects the disposed objects and frees up the memory.  As I discussed above there are two memory worlds in the operating system, native memory, and managed memory. Sometimes garbage collectors cannot do their job, because some of the dot net objects may be holding reference to native objects or vice versa. In such cases, it is difficult to understand where the memory leak is happening. So this is where the profiles come into the picture.  Prerequisites: Visual Studio (Mac or Windows) Enterprise license Device or emulator Download And Installation: Step 1: Download and install the profiler for windows from the below link https://docs.microsoft.com/en-us/xamarin/tools/profiler/?tabs=macos#download-and-install Step 2: Click on the Next button on the window Step 3: Click on the checkbox to agree to the license agreement and click next.  Step 4: Choose the destination folder where you want to install the xamarin profiler and click next again.  Step 5: Click on the install button and wait until the installation completes.  Now that we have successfully installed the profiler, we will have to launch it. But before that, we have to enable profiling in our app. Let's discuss that in the next section. Launching Profiler From Visual Studio: Select android project, right-click and select properties, Build ---> Android Debug---> Android options ---> Enable Developer Instrumentation Once the above step is completed, open visual studio and load your application and keep the app in default debugging mode. Now go to Analyze---> Xamarin Profiler. Once you click on xamarin profiler, the profiler starts profiling automatically.In case you don't see the xamarin profiler option, check the troubleshooting guide in the below link. Xamarin Profiler Troubleshooting - Xamarin Deep Dive Into Profiler Instruments: Xamarin profiler consists of three main instruments for profiling and they are allocations, cycles and time profiler. Let us understand how each of them works. 1. Allocations: Allocations chart is at the top of the profiler as shown in the below figure. Allocations represent the amount of memory being collected by the garbage collector at regular intervals of time during profiling. This instrument uses three data views that help the developer to understand how much of the memory is being used and released. Allocations: This represents the memory allocated by the classes and their associated methods. When you select a class, it shows the memory allocated to that particular classCall Tree: This displays the call tree of the threads used in the application. In other words, it shows the memory allocated to each thread.  Snapshots: This section displays what memory is retained and released. To generate this information, you need to click on the camera button on the toolbar as shown in the below figure. The snapshots information can be captured only during live profiling.  2. Time Profiler: This instrument represents the amount of time taken by each method in the application. The application is paused at regular intervals and a stack trace is run on each thread. 3. Cycles: We often never dispose of the objects as sometimes they will be holding a reference to other objects. The cycles instrument represents the cycle of these objects in the application.  Part B: Memory Management: Introduction: When it comes to a mobile application or a website, it is always necessary to ensure proper management of objects and resources to avoid sluggishness when using the app. If not taken care of, it would lead to slow performance and crashes when used continuously. In this article, I will discuss how to prevent memory leaks and improve the performance of the app. Common Memory Leaks: Memory leaks can be very dangerous because they lead to crashes if allocated memory is full. They can show down the app performance and sometimes make it unresponsive. Let us see a few of the common memory leaks that we make while developing our applications. Subscribing or registering to event handlers, delegates and messaging centers can cause memory leaks if not unsubscribed and unregistered at the right place.  Using views, example  buttons and images cause a memory leak because the garbage collector does not collect them until they are disposed of. Caching mechanisms to store data can cause out of memory exceptions because the memory keeps filling up and the app crashes. Threads should be used carefully because any reference objects will not be collected by the garbage collector.  Using static variables, events are GC roots and are not collected by the garbage collector.  Using bindings can cause memory leaks. So always bind to the dependency object or INotifyPropertyChanged to avoid memory leaks. Avoid using bindings in unnecessary places. Steps for preventing memory leaks: Below are a few approaches to avoid memory leaks. They not only improve the performance of the app, but also reduce the work done by the CPU. Let’s discuss them one by one.  1. Use of Asynchronous operations: We can use asynchronous operations to many of our functions especially for long-running tasks. Asynchronous operations do not block the UI thread and ensure a smooth transition of user interactions. To enable asynchronous operations, dot net provides async and await keywords which can be used to call asynchronous APIs.  2. Reducing the application size: In order to reduce the application size, we need to understand the compilation process of each platform.  Android uses a just-in-time (JIT) compiler to convert to an intermediate language. Windows uses a built-in-time compiler to convert to an intermediate language. Ios uses an ahead-of-time compiler to convert to ARM assembly language.  For all of these platforms, appropriate linker options should be selected in order to strip off the unused framework class. By default, in xamarin the linker is disabled. We need to enable the correct linker so that during the run time, the application determines which members, types are used and removes the unused types. To understand how to select an appropriate linker, go through the below link Cross-Platform Performance - Xamarin 3. Optimizing image assets: Images are the most expensive resources an application can have as we use them at high resolutions and they occupy a lot of memory. We need to optimize images based on the phone resolution by having different resolutions and fit them based on the phone size. For example, use a small resolution image if you are using it in a listview rather than a big image that fits a full screen because there is a lot of CPU wastage to decode them to smaller sizes. Also, use the images only when required and release them when not in use. 4. Profilers: Profiler is a great tool to analyze the application behavior and check for memory leaks. They can also be combined with native instruments to check memory allocations of native objects. I hope you already know how to use them as we have discussed xamarin profilers in PART- A. 5. Test for memory leaks in the app: It is always best practice to test memory leaks for every function you do. Below is the sample code to test memory leaks. [Test]         void MemoryLeakTest()         {            var weakReference = new WeakReference(leakyObject)             GC.Collect();             GC.WaitForPendingFinalizers();             GC.Collect();             Assert.IsFalse(weakReference.IsAlive);         } 6. Unsubscribe from events: It is always best practice to unsubscribe from events to dispose of them so that the garbage collector does its job. We often forget to do that and this leads to memory leaks as the object is still holding the reference and keeps it alive. This has to be taken care of whenever using threads, messaging center, event handlers, and delegates. Below is the sample code to unsubscribe from events and dispose of them public class EventDemo     {         public event EventHandler DemoEvent;         public void OnMyEventFires()         {             if (DemoEvent != null)             {                 DemoEvent(this, EventArgs.Empty);             }         }     }     public class SubscriberDemo : IDisposable     {         readonly EventDemo  eventDemo;       public SubscriberDemo(EventDemo  _eventDemo)        {           eventDemo = _eventDemo;             eventDemo.DemoEvent += OnDemoEventFires;         }         void OnDemoEventFires(object sender, EventArgs e)         {             Debug.WriteLine("The publisher notified the subscriber of an event");         }        public void Dispose()         {             eventDemo.DemoEvent -= OnDemoEventFires;       }     }Using Dispose Pattern: The dispose method is used to release unmanaged resources. Our garbage collector does not allocate or release unmanaged memory. The pattern for releasing these objects is called a dispose pattern. In order to use the dispose method, you need to inherit your class with IDisposableInterface.  Below is the code snippet showing how to use dispose method.   public void Dispose()      {          // Dispose of unmanaged resources.          Dispose(true);          // Suppress finalization.          GC.SuppressFinalize(this);      } Using Statement: Whenever working with files, steam readers, graphics in .Net framework, we create a lot of unmanaged code. By implementing the using statement, the code is transformed into a try/finally statement behind the scenes and the dispose method is called at the final clause. So ensure that you implement “using statement” whenever necessary.  public void CreateFile()      {          using (var stream = new FileStream(@"\Document\YourFile.txt",                                             FileMode.OpenOrCreate))          {              // do your stuff              }// stream.Dispose()       } Size Reduction Techniques: Below are a few approaches to reduce the application size. Always generate the build in release mode. Make sure the LLVM compiler is used. Enable the appropriate linker in each project (Link all for ios projects and Link all assemblies for android projects) Reduce the number of architectures to avoid FAT binary being produced. Reducing Web Service Communication: We often make multiple calls over the web in order to transfer and receive data. This communication uses more network bandwidth and drains the phone's battery. As a result, there is a performance hit on our application. There are a few approaches that can help us here. The JSON format is always preferred as it uses lesser bandwidth while sending and receiving data over the network. Using data transfer objects (DTO) during data transfer between the mobile application and web service because more data can be transferred in a single remote call; thereby reducing the number of network calls. Once the web service call is made, it is preferred to cache the data locally instead of requesting the server multiple times. One more approach to reduce the network bandwidth is to compress data before transferring it over the network. However this might increase the CPU usage and drain the battery. Therefore this approach must be carefully evaluated before using it.  Conclusion: To sum up the things we have covered, we now know what causes memory leaks, how to prevent them and how to use xamarin profiler to find memory allocations, improve application performance and do code optimization. So let us adapt to a routine to bring out these practices while building mobile applications.  I hope this article helps you and saves a lot of time. Please do share your feedback and let me know if you have any queries. 

Xamarin Profiler and Memory Management

8K
Xamarin Profiler and Memory Management

App memory management has become one of the key priorities for any developer today. With new-gen energy-efficient processors launching every day &  operating systems shifting towards efficient power usage along with sleek UI experience, today’s developers face a challenge of developing apps that are sleek & efficient in memory management along with an intelligent tool to check memory leakage proactively. In this article, I will be covering two major topics i.e. xamarin profiler (Part 1) and memory management (Part 2). 

Part 1: Xamarin Profiler 

Introduction to Xamarin Profiler: 

Xamarin Profiler is a tool developed by Microsoft that helps the developers to analyze the app's behavior, and its memory allocations with the help of a visual studio. It is a graphical interface that supports doing profiling in android, iostvos, mac applications in mac and android, iostvos applications in windows.  

Why use a profiler: 

We all know that sometimes we don't properly dispose of the objects and therefore the garbage collector will not collect them and remove them from the memory.  

 In other words, with the help of the profiler, we can check memory leaks that are being held by objects which should ideally be disposed of.  Before that, let's understand how the operating system manages the memory. 

Xamarin Profiler and Memory Management

There are two types of memory, native memory and managed memory. All the ios and android related objects like views, example buttons, text views fall into the native memory and the dot net-related objects, for example, subscriptions, event handlers, threads go into managed memory. Whenever there is a process, the operating system gives a small piece of this memory chunk to xamarin mono. So in order to check the memory allocations of managed memory, we need a profiler.  

Garbage Collector:

 Before getting started with the profiler, let's understand what a garbage collector is. The garbage collector collects the disposed objects and frees up the memory.  As I discussed above there are two memory worlds in the operating system, native memory, and managed memory. Sometimes garbage collectors cannot do their job, because some of the dot net objects may be holding reference to native objects or vice versa. In such cases, it is difficult to understand where the memory leak is happening. So this is where the profiles come into the picture.  

Prerequisites: 

Visual Studio (Mac or Windows) 

Enterprise license 

Device or emulator 

Download And Installation: 

Step 1: Download and install the profiler for windows from the below link 

https://docs.microsoft.com/en-us/xamarin/tools/profiler/?tabs=macos#download-and-install 

Step 2: Click on the Next button on the window Xamarin Profiler and Memory ManagementStep 3: Click on the checkbox to agree to the license agreement and click next.  

Xamarin Profiler and Memory Management

Step 4: Choose the destination folder where you want to install the xamarin profiler and click next again.  

Xamarin Profiler and Memory Management

Step 5: Click on the install button and wait until the installation completes.  

Xamarin Profiler and Memory Management

Xamarin Profiler and Memory Management

Now that we have successfully installed the profiler, we will have to launch it. But before that, we have to enable profiling in our app. Let's discuss that in the next section. 

Launching Profiler From Visual Studio: 

Select android project, right-click and select properties, 

Build ---> Android Debug---> Android options ---> Enable Developer Instrumentation 

Once the above step is completed, open visual studio and load your application and keep the app in default debugging mode. Now go to Analyze---> Xamarin Profiler. Once you click on xamarin profiler, the profiler starts profiling automatically.

Xamarin Profiler and Memory Management

In case you don't see the xamarin profiler option, check the troubleshooting guide in the below link. 

Xamarin Profiler Troubleshooting - Xamarin 

Deep Dive Into Profiler Instruments: 

Xamarin profiler consists of three main instruments for profiling and they are allocations, cycles and time profiler. Let us understand how each of them works. 

1. Allocations: Allocations chart is at the top of the profiler as shown in the below figure. Allocations represent the amount of memory being collected by the garbage collector at regular intervals of time during profiling. This instrument uses three data views that help the developer to understand how much of the memory is being used and released. 

  • Allocations: This represents the memory allocated by the classes and their associated methods. When you select a class, it shows the memory allocated to that particular class

Xamarin Profiler and Memory Management

  • Call Tree: This displays the call tree of the threads used in the application. In other words, it shows the memory allocated to each thread.  

Xamarin Profiler and Memory Management

  • Snapshots: This section displays what memory is retained and released. To generate this information, you need to click on the camera button on the toolbar as shown in the below figure. The snapshots information can be captured only during live profiling.  

Xamarin Profiler and Memory Management

2. Time Profiler: This instrument represents the amount of time taken by each method in the application. The application is paused at regular intervals and a stack trace is run on each thread. 

Xamarin Profiler and Memory Management

3. Cycles: We often never dispose of the objects as sometimes they will be holding a reference to other objects. The cycles instrument represents the cycle of these objects in the application.  

Xamarin Profiler and Memory Management

Part B: 

Memory Management: 

Introduction: When it comes to a mobile application or a website, it is always necessary to ensure proper management of objects and resources to avoid sluggishness when using the app. If not taken care of, it would lead to slow performance and crashes when used continuously. In this article, I will discuss how to prevent memory leaks and improve the performance of the app. 

Common Memory Leaks: Memory leaks can be very dangerous because they lead to crashes if allocated memory is full. They can show down the app performance and sometimes make it unresponsive. 

Xamarin Profiler and Memory Management

Let us see few of the common memory leaks that we make while developing our applications. 

  • Subscribing or registering to event handlers, delegates and messaging centers can cause memory leaks if not unsubscribed and unregistered at the right place.  
  • Using views, example  buttons and images cause a memory leak because the garbage collector does not collect them until they are disposed of. 
  • Caching mechanisms to store data can cause out of memory exceptions because the memory keeps filling up and the app crashes. 
  • Threads should be used carefully because any reference objects will not be collected by the garbage collector.  
  • Using static variables, events are GC roots and are not collected by the garbage collector.  
  • Using bindings can cause memory leaks. So always bind to the dependency object or INotifyPropertyChanged to avoid memory leaks. Avoid using bindings in unnecessary places. 

Steps for preventing memory leaks: 

Below are a few approaches to avoid memory leaks. They not only improve the performance of the app, but also reduce the work done by the CPU. Let’s discuss them one by one.  

1. Use of Asynchronous operations: We can use asynchronous operations to many of our functions especially for long-running tasks. Asynchronous operations do not block the UI thread and ensure a smooth transition of user interactions. To enable asynchronous operations, dot net provides async and await keywords which can be used to call asynchronous APIs.  

2. Reducing the application size: In order to reduce the application size, we need to understand the compilation process of each platform.  

Android uses a just-in-time (JIT) compiler to convert to an intermediate language. 

Windows uses a built-in-time compiler to convert to an intermediate language. 

Ios uses an ahead-of-time compiler to convert to ARM assembly language.  

For all of these platforms, appropriate linker options should be selected in order to strip off the unused framework class. By default, in xamarin the linker is disabled. We need to enable the correct linker so that during the run time, the application determines which members, types are used and removes the unused types. 

To understand how to select an appropriate linker, go through the below link 

Cross-Platform Performance - Xamarin 

3. Optimizing image assets: Images are the most expensive resources an application can have as we use them at high resolutions and they occupy a lot of memory. We need to optimize images based on the phone resolution by having different resolutions and fit them based on the phone size. For example, use a small resolution image if you are using it in a listview rather than a big image that fits a full screen because there is a lot of CPU wastage to decode them to smaller sizes. Also, use the images only when required and release them when not in use. 

4. Profilers: Profiler is a great tool to analyze the application behavior and check for memory leaks. They can also be combined with native instruments to check memory allocations of native objects. I hope you already know how to use them as we have discussed xamarin profilers in PART- A. 

5. Test for memory leaks in the app: It is always best practice to test memory leaks for every function you do. Below is the sample code to test memory leaks. 

[Test] 
        void MemoryLeakTest() 
        { 
           var weakReference = new WeakReference(leakyObject) 
            GC.Collect(); 
            GC.WaitForPendingFinalizers(); 
            GC.Collect(); 
            Assert.IsFalse(weakReference.IsAlive); 
        }

6. Unsubscribe from events: It is always best practice to unsubscribe from events to dispose of them so that the garbage collector does its job. We often forget to do that and this leads to memory leaks as the object is still holding the reference and keeps it alive. This has to be taken care of whenever using threads, messaging center, event handlers, and delegates. Below is the sample code to unsubscribe from events and dispose of them 

public class EventDemo
    {
        public event EventHandler DemoEvent;
        public void OnMyEventFires()
        {
            if (DemoEvent != null)
            {
                DemoEvent(this, EventArgs.Empty);
            }
        }
    }
    public class SubscriberDemo : IDisposable
    {
        readonly EventDemo  eventDemo;
      public SubscriberDemo(EventDemo  _eventDemo)
       {
           eventDemo = _eventDemo;
            eventDemo.DemoEvent += OnDemoEventFires;
        }
        void OnDemoEventFires(object sender, EventArgs e)
        {
            Debug.WriteLine("The publisher notified the subscriber of an event");
        } 
       public void Dispose()
        {
            eventDemo.DemoEvent -= OnDemoEventFires;
       }
    }

Using Dispose Pattern: The dispose method is used to release unmanaged resources. Our garbage collector does not allocate or release unmanaged memory. The pattern for releasing these objects is called a dispose pattern. In order to use the dispose method, you need to inherit your class with IDisposableInterface.  Below is the code snippet showing how to use dispose method.  

 public void Dispose() 
    { 
        // Dispose of unmanaged resources. 
        Dispose(true); 
        // Suppress finalization. 
        GC.SuppressFinalize(this); 
    } 

Using Statement: Whenever working with files, steam readers, graphics in .Net framework, we create a lot of unmanaged code. By implementing the using statement, the code is transformed into a try/finally statement behind the scenes and the dispose method is called at the final clause. So ensure that you implement “using statement” whenever necessary.  

public void CreateFile() 
    { 
        using (var stream = new FileStream(@"\Document\YourFile.txt", 
                                           FileMode.OpenOrCreate)) 
        { 
            // do your stuff   
 
        }// stream.Dispose()  
    } 

Size Reduction Techniques: Below are few approaches to reduce the application size. 

  • Always generate the build in release mode. 
  • Make sure the LLVM compiler is used. 
  • Enable the appropriate linker in each project (Link all for ios projects and Link all assemblies for android projects) 
  • Reduce the number of architectures to avoid FAT binary being produced. 

Reducing Web Service Communication: We often make multiple calls over the web in order to transfer and receive data. This communication uses more network bandwidth and drains the phone's battery. As a result, there is a performance hit on our application. There are a few approaches that can help us here. 

  • The JSON format is always preferred as it uses lesser bandwidth while sending and receiving data over the network. 
  • Using data transfer objects (DTO) during data transfer between the mobile application and web service because more data can be transferred in a single remote call; thereby reducing the number of network calls. 
  • Once the web service call is made, it is preferred to cache the data locally instead of requesting the server multiple times. 
  • One more approach to reduce the network bandwidth is to compress data before transferring it over the network. However this might increase the CPU usage and drain the battery. Therefore this approach must be carefully evaluated before using it.  

Conclusion: 

To sum up the things we have covered, we now know what causes memory leaks, how to prevent them and how to use xamarin profiler to find memory allocations, improve application performance and do code optimization. So let us adapt to a routine to bring out these practices while building mobile applications.  

I hope this article helps you and saves a lot of time. Please do share your feedback and let me know if you have any queries. 

Mounika

Mounika Rajapuram

Module Lead

Mounika calls herself a dynamic professional with expertise in developing mobile applications for iOS and Android. With C# and Xamarin as primary areas of expertise, she also likes to dwell in doodle art in her pastime.

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

7 Things to Keep in Mind Before Your Next Web Development Interview

Websites are an integral component of any business. According to research by techjury, there are approximately 4.3 billion internet users in the world, which makes the internet the single largest source for an audience. Organizations have identified this factor, and every business today has a website that represents them online. In fact, many companies, like ecommerce stores and food and beverage companies, for example, make their largest profits directly from their website.The requirement for website development, revamping and maintenance makes web developers sought-after candidates for every company. As a web developer, your options are many, and by regularly upskilling yourself, you can ensure a lucrative career. Before you attend your next interview, make sure to go through interview questions and answers online to be prepared. In this article, we cover seven tips for web developers to crack their next interview.1. Learn how to design In most companies, design and development are handled by different teams, and rightly so since they are two different disciplines that require a different skillset. The former is in the creative field, and the latter is technical. However, a candidate who can handle both is always going to be preferred. As a developer, you need to know the basics of design, the rules of UI and UX, and understand brand guidelines. These basic design skills will help you be more involved in the project and be a plus point to crack your next interview.  2. Be proficient in basic languages Every web developer needs to have a strong grasp on the ground level languages: HTML, CSS, PHP and JavaScript. Whether you develop on WordPress or code in Angular, your knowledge on these four languages will be tested. Prepare by going through knowledgebase articles for each of these and looking for interview questions online, especially JavaScript interview questions because a lot of companies look for animations that are triggered through JavaScript. 3. Learn multiple platforms Technology is ever-evolving. Make it a point to stay updated and learn new languages on a regular basis. Many websites and web apps today are built on different platforms: AngularJS, Python, React, Django, etc. Knowing more than just the basic languages will give you an edge over other candidates and pave the way for faster career growth. 4. Learn the basics of editing tools We have already discussed how important it is to add design as a skill to your portfolio. One way to do this would be to learn how to use editing tools such as Photoshop and Illustrator. This will also reduce your dependency on the design team whenever you need basic design edits like resizing or recolouring of images or layouts. Not only will you be able to complete projects faster, but you will also add bonus skills to your resume that interviewers pick up on.  5. Create an online portfolioThe best resume for a web developer is a website! If you can create a visually stunning website that is also agile, you can impress interviewers just by showcasing it. An online portfolio is a great way to show in real-time what you’re capable of, and also to showcase all your previous projects. It also helps potential employers find you online.  6. Be prepared to create a mock website Companies nowadays place a premium on seeing you walk the talk. Rather than asking you a bunch of questions, they give you a single page design and ask you to develop it at the interview. There usually aren’t any restrictions and interviewers let you choose the language and platform (unless the interview is for a specific language). Go into the interview prepared for this scenario by deciding beforehand what your strengths are and what platform you can complete this task on within the fastest time possible.  7. Relax, there are plenty of opportunities We began this article by giving you an idea of how much in demand web developers are. With many start-ups springing up and companies constantly revamping their websites, there are going to be numerous opportunities for you to land a well-paying web developer job. You can also look for freelance projects online on websites like Fiverr. Ace your next web development interview These are some core areas that every web developer needs to be proficient at. With the stiff competition today, mastering just one skill is never enough. Fortunately, there are a plethora of online courses and articles that will help you prepare and bag a career-defining web development job.
6650
7 Things to Keep in Mind Before Your Next Web Deve...

Websites are an integral component of any business... Read More

Why ReactJS is taking over Frontend Development

History of JavaScript Today, we see JavaScript used pretty much everywhere. For the seventh year in a row, we see it ranking as the most popular and widely used programming language, a good 67.8% of developers having used it in 2019. JavaScript is used to build 95.2% (1.52 billion) websites today, including Facebook and YouTube and some of the most popular and useful apps such as Google Maps and eBay. Let’s take a closer look at what JavaScript is, how and why it was created, and how it seems to be taking over front-end development. It all began in the late 90s when Netscape Navigator, a popular browser was launched by Netscape Communication. In the initial days of Netscape, it was just a software which was able to render static HTMLs, but people wanted it to do more. Netscape envisioned that web pages should be more dynamic in nature. If users are not able to engage with HTMLs, browsers will end up becoming boring pieces of software, they figured.That’s when Brendan Eich came into the picture. He was contracted in 1995 by Netscape Communications to develop a language which would have a low learning curve, so that anyone would be able to write functionalities with it. He developed the language in just 10 days and named it Mocha. A working prototype of Mocha was integrated in the Netscape Browser in May 1995, renaming the language to LiveScript and later in December 1995, it was renamed again, this time as JavaScript. The marketing team at Netscape chose to call it "JavaScript" as Java was extremely popular at that time. With the popularity of Netscape Navigator, Microsoft wished to capture the browser market and developed Internet Explorer with a scripting language named JScript. For a long time, there was no common standard formed for JavaScript, resulting in huge cross browser compatibility issues. Finally, in 1997, Netscape invited ECMA (European Computer Manufacturing Association) to take the responsibility of forming a specification for JavaScript.Since then, the ECMA has released updated specifications for JavaScript regularly and browsers try to follow these specifications in their implementation of JavaScript engine.Fact Check: Today, Brendan Eich is the CEO of Brave Software which builds a privacy oriented, chromium-based browser named Brave.Fact Check: Netscape Navigator later became the foundation stone for Mozilla Firefox. They retained the same name for their JavaScript engine "Spider Monkey" which was part of the Netscape navigator.Need of Framework With the ECMAScript specifications in place, developers began to use JavaScript  to make the HTML page much more dynamic using JavaScript. However, there were still a few developers who preferred to write big client-side functionality with JavaScript, owing to low performance of browser and JavaScript engines. Perhaps, the industry had a more a server-side performance focus in that era. Then, as computers became more powerful, browser performance improved and JavaScript engines evolved, developers started moving client-side logic to browser using JavaScript.Once developers started writing more and more JavaScript, the community felt the need to write logic in a more structured and scalable manner, so as to be more understandable, readable, manageable and less error prone. The need for a framework in JavaScript was clearly felt.Many frameworks like Dojo, Backbone, Ember and AngularJS eventually emerged within their own communities, which tried to solve problems in their unique way. Collectively, this has helped the whole JS community to move forward towards a more scalable and maintainable web application. ReactJS In 2011, Codebase for Facebook Ads was getting bigger. Developers began to face maintenance issues with it and it was getting harder to add new features in an efficient way. That's when Facebook engineer, Jordan Walke, built a prototype for an efficient application UI. This marked the birth of ReactJS, initially called FaxJS. Later, when Instagram was acquired by Facebook, the folks at Instagram wanted to adopt this framework. Pete Hunt and Jordan Walke then improved, decoupled the library and made it open source as ReactJS in 2013. Since then ReactJS has gone through many changes. The latest version of ReactJS in 2020 is currently 16.13. ReactJS follows component-based architecture and encourages developers to think in terms of small, composable components. Interestingly, this methodology is aligned with an efficient approach for solving any problem in life: the first step to solve a big problem is to break it down into multiple smaller sub problems. Once you have a solution for each sub-problem, you can then add it up to get the overall solution. This can be applied to all problems, big or small. ReactJS asks developer to adopt a problem-solving approach like this to build any UI. It must be noted that ReactJS does not aim to solve each and every problem of building a web application. Rather, it has a narrow focus and a limited scope to solve the one core problem of web development around how to efficiently updating the UI/views.When ReactJS was open sourced in the JSConf 2013, the ideas and changes that ReactJS was proposing were not very well received. For instance, although two-way binding was very popular, ReactJS went ahead with one way data flow. In another example, writing HTML inside JS was considered a bad practice, but ReactJS still wanted to use JSX. All these ideas initially attracted a lot of criticism from the web developer community. In time, however, developers started using it and found it easy to build components efficiently. So, ReactJS now solved the one problem around updating views. But what about all the problems in web development? An ecosystem began to emerge to address the other problems along with ReactJS. Libraries like Redux and React-Router came to life, making ReactJS a complete web framework, although this meant that there would be a dependency on multiple libraries. The ease of using ReactJS trumped all the negative points of the framework and this is what continues to make it a very popular library in web development. In 2020, ReactJS has 50K plus stars on Github and is downloaded 6 million times per week. The ReactJS ecosystem continues to grow steadily; React Native recently bought ReactJS to build cross mobile platform apps. Libraries like Gatsby and NextJS encourage developers to use ReactJS on server and provide benefits of server-side rendering without much hassle. ReactJS has also stood out in multiple developer surveys such as the State of JavaScript. Main design concepts in ReactJS Main design concepts in ReactJSDeclarative, composable, reusable componentsReactJS motivates developers to write small components and reuse the same component at multiple places. Re-usability of components greatly speeds up the overall development and results in less amount of code. Less code is always better because it is less prone to errors. ReactJS encourages developers to write composable components which can be wrapped around any other React component to provide special functionality, thus discouraging the writing of components that do too many things. ReactJS always encourages developers to break their problem into smaller problems, solve the smaller problems first and then combine them to present the overall solution. Less functionality in components always leads to less error prone components. ReactJS encourages developers to write clean, readable, and maintainable code. This is why it emphasizes writing declarative components, which make a codebase easier to read and understand by fellow developers.Declarative, composable components looks a lot like HTML in JS. Instead of standard HTML tags, we have React components as tags. This similarity to standard web semantics is what makes JS somewhat familiar to developers starting out. Reactive Updates Writing static HTML is no fun and it can be said that JavaScript was born to bring interactivity to web pages. ReactJS helps developer to add functionalities in components with which the user can interact and see the results. ReactJS allows developers to attach a state to component and whenever the state of components changes, the component efficiently re-renders itself to produce an updated view. Now, the state of the component can be changed by clicking a button, entering text into the input box or any other part of the component triggering an event. The React component listens to these events and acts accordingly. Updating the whole component UI seems like a terrible idea, but ReactJS has implemented this terrible idea wonderfully by doing it efficiently. In-memory DOM representation ReactJS is able to efficiently update views by keeping a DOM representation in memory known as virtual DOM. Upcoming updates always compare the new DOM with an older copy of the DOM and based on the difference, it figures out the actual DOM elements which need to be updated on the UI. Reducing the number of DOM manipulations makes ReactJS faster. What this means is that writing smaller React components will take up less memory to store DOM representations (Virtual DOM) and ultimately, this results in better performance. Features of ReactJS Main features of ReactJSJSX and Why is it needed When ReactJS was released, it was mentioned in documentation that it is recommended to use JSX along with ReactJS. Now, what is JSX? and do i really need another library to use the ReactJS library? So, let us see how a simple ReactJS component looks without JSX: import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); There is no way the above code looks like a declarative component. The truth is JavaScript does not understand HTML or XML like tags. That is why we need someone to do that conversion for us. Here enters JSX, also known as a syntax extension for JavaScript. With JSX, the above Greeting React component will look something like this: import React from "react";  function Greeting({ name }) {    return {`Hello ${name}`};  }  ReactDOM.render(, document.getElementById("root")); JSX actually makes ReactJS code more readable and understandable. You can assume this as a templating library which converts HTML looking syntax into ReactJS element JS code by calling createElement(). Virtual DOM ReactJS has made the term, 'VDOM' or virtual DOM very popular in the JavaScript community. Web browsers have provided APIs to interact with DOM to make our web page dynamic. One can dynamically add or remove nodes in the web page by using these APIs. But interacting with these APIs was very slow, as changing node triggers re-layout and re-paint event for sub-tree. Although the entire subtree is re-rendered (diffing stops when an element type has been modified and subtree is freshly rendered), even in case of virtual DOM reconciliation, the advantage that React offers is that the developer is freed from figuring out which part of DOM really requires updates - the diffing and reconciliation algorithm takes care of it.  React has thus provided a way to reduce the number to change in DOM using virtual DOM. The VDOM is a JavaScript object which contains information of DOM sub tree. We can also call this an object representation of DOM. React uses this object to compare subsequent modification and figure out the minimum number of modifications needed to make in browser DOM to get the desired result. ReactJS claims that the wonderful performance of their library is because of the algorithm they use to compare the virtual DOM. React Native React native is another popular library which is used to build cross platform mobile applications using JavaScript. Before ReactJS, Cordova and ionic were some frameworks which were very popular to build mobile applications using JavaScript. However, these applications did not perform very well. React native uses popular component-based concepts of ReactJS and provides a way to build an efficient mobile application. React native converts JS code into native platform code to run in mobile devices. This approach has improved the performance of mobile applications by a great deal in comparison to other frameworks like ionic. With React Native, ReactJS has now become a very popular library to build UI on any platform. ReactJS: Here to stay Over the past decade, the JavaScript community has seen tremendous changes in language within the developer community. It has seen a lot of new ideas and terms surface in the form of libraries. Developers are building and sharing their work with rest of the world quite frequently and every other day, implementations are open sourced on Github. These new ideas and the problem solving approach continues to help the JavaScript ecosystem to evolve and become better. Prior to ReactJS, JQuery was very popular and was the default library for any web project involving DOM manipulation. With AngularJS and other MVC libraries, we were encouraged to think about a problem in terms of Modal, View and Controller. People have always sought to figure out an approach that can solve the problem. And structuring a solution in a scalable manner is not a new challenge either. We have already implemented scalable solutions at server-side, and they are performing quite well. ReactJS now brings the same pattern to the front-end, where the final output is a UI. To implement this, we break the problem into smaller sub-problems and write solutions for them. This is the basic mental model to solve all UI problems and ReactJS focuses on the same. New ideas in the JavaScript community help the community move forward and eventually, the best solutions become part of the standard JS (ECMAScript). ES modules, promises and some lodash utilities are examples of this. When a library moves in the same general direction as the web, it is bound to be used by a large community. Developers will use these solutions until new specifications are finalized and browsers adopting new specifications. Interim, people will use the feature in the form of third party library.So, is ReactJS moving in the right direction? I would say yes. ReactJS is evolving right along the evolving standards of JavaScript. The front-end community is leaning more towards concepts of functional programming rather than object-oriented methodology. In a similar direction, ReactJS continues to move towards a functional programming pattern. ReactJS has introduced hooks in version 16.8, which encourages developer to build more and more functional components instead of class-based components. Hook does not even work with class-based component. Understanding well that it sometimes becomes a hectic task to figure out which library one should choose to handle state management, ContextAPI and useReducer hooks have been introduced, which help in managing state in small applications much better. Today, with the help of ContextAPI and useReducer hooks, you can build an application without using any other library like Redux. This, however, does not mean that you should stop using Redux as it has its own benefits.Component based architecture is also aligned with the standard web components support in browsers, which allow developers to write non-standard HTML tags in code. In short, ReactJS has made the community become familiar with some of the upcoming web standards. For this reason, I feel that conceptually, ReactJS is going to stay with the community for long. Many big companies like Facebook, Microsoft and AirBnB are supporting the direction and concepts of ReactJS, thus adding credibility to the library. With many big brains backing the library, the ReactJS community looks poised for growth. With no perfect solution to all the problems in web development in sight, the best option is to move forward with whatever is available at the moment. In the JavaScript community too, there is an effort to figure out an alternate to ReactJS such as VueJS and Svelte. Perhaps, ReactJS will get replaced by some other library in the future. However, the basic idea of creating smaller, reusable components is here to stay.Whatever framework we learn, it is most important to grasp the basic idea behind the library. It is this idea or design pattern that is going to remain for good. It may appear in front of you in a different form and shape, but the idea will remain forever. 
9958
Why ReactJS is taking over Frontend Development

History of JavaScript Today, we see JavaScript u... Read More

Exploring the Various Decorators in Angular

There are several important concepts in Angular, and Decorators are an important concept to learn when you are working with version 2 and above of Angular. Through this post we will learn about decorators, its types and how it is being used in real time applications.  Decorators are an important concept in TypeScript and since Angular uses Typescript widely, decorators become an important part of Angular as well.  What are Decorators? Decorators are functions that are invoked with a prefixed @ symbol, and are immediately followed by a class, method or property. They allow a service, directive or filter to be changed before being used. Basically, a decorator provides configuration metadata that determines how the component, class or a function should be processed, instantiated and used at runtime. Angular defines a number of decorators that attach specific kinds of metadata to classes, so that the system knows what those classes mean and how they should work. There are various types of in-built decorators. Let’s look at each type of decorator in detail. Types of Decorators: There are four types of decorators and each type further has its own subset of decorators.  Class Decorators  This is the first type of decorator which tells us about a particular class’s intent and helps answer questions like whether the class is a component or a module. There are various Class decorators in Angular, and among them @Component and @NgModule are widely used. Let’s see the structure of class decorators via a code snippet. Explanation: The below code snippet uses @Component, which is a type of class decorator provided by Angular.Property Decorators Property decorators are used to decorate specific properties inside a class. Using a property decorator, we can easily identify why we use any particular property of a class Like @Input (), @Output, @ReadOnly (), @Override () The above code uses @Override decorator before the property name which will invoke the decorator. This is nothing but a function and will override the string property name from “pat” to “test”. Method Decorator  Method decorators, as the name indicates, are used to decorate the method defined inside our class with functionality. A common example of method decorator is @HostListener In the above screen shot @HostListener decorator is used before onHostClick () method. Parameter Decorators Parameter decorators allow us to decorate parameters in our class constructors.  @Inject () is a common and widely used parameter decorator. Using this decorator, we can inject services in Angular classes. Structure of Decorators  In all the code snippets that we have seen so far on decorators, you must have noticed that each of the decorators follows a similar pattern or structure when used in code. Each decorator starts with @ symbol and is added before the class, method, property or passed as a parameter. All are functions having open and close brackets. This helps us understand that it is the function which is used as an in-built decorator. Just like a function can be customized, decorators can also be customized. Based on the requirement in our project, we can create custom decorators and use them accordingly. Custom Decorator  In this section we are going to learn the steps involved in creating custom decorators. As the term custom itself suggests, it is something which we create based on our project need which is not already fulfilled by the in-built Angular decorator. So, whenever we want to add some more features to our class, property of class, or method of class we use custom decorators. Here we are going to create a custom class decorator. Step 1. In an Angular project solution structure, create a classes folder inside the app folder.  Inside the classes folder create a class named sample Demo . Step 2. Once the class is created, you can go ahead and create a folder inside the app folder called decorator and add a file name as class.decorator.ts  Step 3. As we know decorators are functions, so we will create a function named Logging, as follows: ‘target’ is the class on which this decorator is going to be used and as we are going to use this decorator on class sample Demo, we have added export keyword before this function. Step 4. As we are going to use this decorator in the sample demo, let us add the sample demo class with decorator.  If we add this class in our main component and invoke, we will see the output on console as custom decorator SampleDemo How to pass data to a decorator The example explained above is a simple custom decorator where we are logging some messages on the console along with the class name where it is used. But if we want to send messages through the class where we are adding the decorator, then we have to change the implementation of the Function Logging.  Function Logging will accept some arguments and return the message as passed by the decorator on class. When we use the decorators in Angular, we pass in some form of configuration, specific to the decorator. For example, when we use @Component we pass through an object, and with @HostListener we pass through a string as the first argument (the event name, such as 'click') and optionally an array of strings for further variables (such as $event) to be passed through to the decorated method. Uses of Decorators in Real Time Applications Almost all Angular applications use decorator concepts; as decorators are functions that allow a service, directive or filter to be modified prior to its usage. @override, @deprecate, @autobind, @mixin are decorators which are widely used in real time applications. Angular framework has several of these kinds of examples which help to achieve complex features in applications. We know now what Angular decorators are and how they work on class, property, methods and parameters to provide information about metadata. All decorators work on a similar principle. We can apply some changes to the behaviour of the default functionality or we can add some custom tweaks to the code before the decorator can be applied to a class, property or method.  There are different ways to call decorators as these decorators can control start from the class implementation to the property and method implementation within the class. Decorators are great when code needs to be customized to suit the needs of the clients and when in-built functions do not help us with what we need.  Summary  When it comes to Angular decorators, we have several options to inject our codes and logic on different levels of class; as everything in programming revolves around class and its objects. Angular, being a rich framework gives us wide options to handle things in our own way. TypeScript has introduced this concept of decorators and those wishing to implement decorators into their code will benefit from going through TypeScript documents to understand more about actual implementation of decorators and its advanced concepts.