<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Evgeny Fedorenko on Medium]]></title>
        <description><![CDATA[Stories by Evgeny Fedorenko on Medium]]></description>
        <link>https://medium.com/@evgenyfedorenko?source=rss-a75caa83b079------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*L_sm8sEW1S-Q8B_NXM4EEw.png</url>
            <title>Stories by Evgeny Fedorenko on Medium</title>
            <link>https://medium.com/@evgenyfedorenko?source=rss-a75caa83b079------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:08:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@evgenyfedorenko/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Read your production Angular Errors like a pro]]></title>
            <link>https://medium.com/angular-in-depth/read-your-production-angular-errors-like-a-pro-32c3df34bdae?source=rss-a75caa83b079------2</link>
            <guid isPermaLink="false">https://medium.com/p/32c3df34bdae</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Evgeny Fedorenko]]></dc:creator>
            <pubDate>Thu, 13 Feb 2020 15:36:42 GMT</pubDate>
            <atom:updated>2020-04-29T18:00:10.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*VyV1p0du41o1fLTm.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>We all want to build bug-free applications. We also know that it is not possible. Therefore the best we can do when we encounter an error is to interpret it as fast as we can and push the fix.</p><p>I am sure this one looks familiar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*zoTys8Hmrc_4UFkrhZdMdA.png" /></figure><p>This is a TypeError thrown from the Angular application which can be seen in the Chrome Developer Tools console tab. Let’s analyze it to understand what is going on:</p><ol><li>The error tells us that there is an attempt to access the property ‘value’ of some variable which at that time holds a <em>null</em> value. If this is not enough for us to know where this code is then we need to dig deeper (this would be the case when ‘value’ property name is too generic and there are multiple places where this could be happening)</li><li>at t.&lt;anonymous&gt; main-es2015.d97d995449352dcdcf91.js:1 is supposed to tell us where the error has occurred in the call stack. Sadly, it does not help much. Since this is production all file/method names are minified and are not readable. Also, the entire file is composed of a single line of massive code chunk therefore reference to the first line in the call stack is also useless.</li></ol><blockquote>When we generate Angular application for production the code gets optimized — <a href="https://angular.io/guide/deployment#production-optimizations">bundled, minified and uglified</a>.</blockquote><p>When we ship the code to production we generally don’t want to include <a href="https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map">source-maps</a> in the build. The above example is no exception. So even if we get lucky and witness this error (which is not always a case because not all users report errors) we are still clueless about it due to the debugging limitations in prod builds.</p><h3>Are we doomed?</h3><p>There are a few problems we need to solve here. Let’s tackle them one by one. For now, why don’t we figure out how can we collect all instances of such errors and store them for later analysis?</p><h4>Logging browser exceptions</h4><p>Angular provides us with a hook for centralized exception handling called <a href="https://angular.io/api/core/ErrorHandler">ErrorHandler</a>. To intercept error handling, we can write a custom exception handler that replaces ErrorHandler default implementation. Consider this example:</p><pre>class MyErrorHandler implements ErrorHandler {</pre><pre>....</pre><pre>handleError(error) {<br>     this.logger.error(error);<br>   }</pre><pre>....<br>}</pre><pre>@<a href="https://angular.io/api/core/NgModule">NgModule</a>({ providers: [{<br>    provide: <a href="https://angular.io/api/core/ErrorHandler">ErrorHandler</a>,<br>    useClass: MyErrorHandler<br>  }]<br>})<br>class MyModule {}</pre><p>This is a simple implementation of our ErrorHandler which uses a logger service to send the error via HTTP POST request to our backend. The error here is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error"><em>Javascript Error.</em></a><em> </em>We are interested in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack">error.stack</a> property.</p><blockquote>The non-standard <strong><em>stack</em></strong> property of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error"><em>Error</em></a> objects offer a trace of which functions were called, in what order, from which line and file, and with what arguments. The stack string proceeds from the most recent calls to earlier ones, leading back to the original global scope call.</blockquote><p>This is how the last element of the stack trace looks when logged in the Browser console:</p><blockquote>main-es2015.d97d995449352dcdcf91.js:1</blockquote><p>We can see here a lineNumber. The other important property is the columnNumber. The console log does not show it. When dealing with production code it is very important to have that information so that we understand the origin of the error.</p><p>Here is how the stack property looks like when being inspected in the Chrome debugger (to achieve this output I hovered over the stack property of the error variable):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tof3o8KEw2ATe4kFkQW3Q.png" /></figure><p>292908 here is the much neededcolumnNumber. And here is why.</p><h4>Reading production error stack trace</h4><p>Now after we have the information about the error which consists of fileName, lineNumber and columnNumber we can interpret its location using <a href="https://www.npmjs.com/package/source-map-cli">source-map-cli</a> tool. It is a command-line interface to the <a href="https://github.com/mozilla/source-map">source-map</a> module.</p><p>Here is how it can be used:</p><h3>resolve [options] &lt;uri&gt; &lt;line&gt; &lt;column&gt;</h3><p>The resolve command accepts a source map (either a path or a URL), a line and column and returns the original source file name, line and column, along with a context (usually the name of the variable or function).</p><p>Since we don’t have source-maps generated we need to build them:</p><p>ng build --prod --sourceMap=true</p><p>This command will produce the build along with the source map files. After that we can run this command <em>(please note, the source map file name will be different from the original corresponding source file b/c new build generates new hash):</em></p><p>source-map resolve dist/main-es2015.0cd3209b74d20b15dbfc.js.map 1 292908</p><p>And finally — it will give you the filename and location of the error:</p><pre>Maps to webpack:///src/app/app.component.ts:33:15 (value)</pre><pre>    return obj.value;</pre><pre>               ^</pre><h3>Conclusion</h3><p>In this short article we learned how to read our production logs.</p><ol><li>We need to store the errors so later we can handle them.</li><li>We can use a nice tool like source-map-cli to get the information about the error in the production optimized source code.</li></ol><h4>Thank you.</h4><p><em>If you liked this article follow me on twitter at @</em><a href="https://twitter.com/e_fedorenko"><em>e_fedorenko</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32c3df34bdae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/read-your-production-angular-errors-like-a-pro-32c3df34bdae">Read your production Angular Errors like a pro</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I wrote NgRx Store in 63 lines of code]]></title>
            <link>https://medium.com/angular-in-depth/how-i-wrote-ngrx-store-in-63-lines-of-code-dfe925fe979b?source=rss-a75caa83b079------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe925fe979b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Evgeny Fedorenko]]></dc:creator>
            <pubDate>Mon, 18 Nov 2019 09:53:51 GMT</pubDate>
            <atom:updated>2020-04-29T20:34:12.857Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep dive into NgRx Store. How I tried to understand it by getting to the very essentials.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RfsOa1RzbyM62pbjBJqDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*OZEOTePlCv83XN7a.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><h4>Why I love NgRx Store</h4><p>I was introduced to a concept of Redux state management back in 2017 when I started working on a new Angular 2 project. I have previously worked on an AngularJS application for a year or so only to witness the project not see a day of light.</p><p>It failed because developers on the team including myself were constantly over-engineering most of the features which could have been shipped much earlier. This slowed down release significantly and eventually failed the project all together.</p><p>There were many problems with that code most of which were contributed from the AngularJS framework design. One of them was state management. The application state was scattered across many singleton services. Those services were injected God knows in how many components which were mutating the state left and right. Oh boy, it was a mess!</p><p>I have to say my initial experience with Redux philosophy was not an easy ride. Simultaneously I was learning Typescript, RxJS and NgRx Store. It was fun but not without a struggle. I wanted to pull my hair off while trying to grasp the idea of Observables written in Typescript used in NgRx. But I liked what I saw and what I was learning. I had a good feeling about the whole thing. The pieces of the puzzle were coming together.</p><p>Since then I became a passionate proponent of Redux and NgRx Store. Its architecture resonated with me on so many levels. I’ve always been mesmerized with how easy it was to use it and yet I have never really bothered to dig deep enough into its source code to learn how it is built. Special thanks to <a href="https://medium.com/u/f7828ad40c7c">Alex Okrushko</a> for adding all the sophisticated Typescript Generics which scared me off every time I dared to open the pandora box.</p><p>Now it is a time to finally get to the bottom of it.</p><h4>Let’s get it coded</h4><p>I have used a super simple <a href="https://stackblitz.com/edit/ngrx-seed">Angular NgRx-Seed app</a> with a single <a href="https://ngrx.io/guide/store/reducers">reducer</a> and <a href="https://ngrx.io/guide/store/actions">action</a> which I was dispatching on the button click — all I wanted to see was how dispatch was calling the reducer and then a particular <a href="https://ngrx.io/guide/store/selectors">selector</a> was aware of the state change. Well, no wonder it is all RxJS magic in action — only this time I was a magician who knew the trick. Now I want to share it with you, my patient reader.</p><p>Here is a <a href="https://gist.github.com/evgenyfedorenko/589f67d3b32afbc035d497dd2a02745e">StoreService</a> I wrote which resembles the NgRx Store but is vastly oversimplified. It covers the basic functionality of dispatching actions, accumulating state and subscribing to updates using selectors. It is coded for illustrative purposes and by no means is intended to be a substitute for a state management library. At least not in its current form.</p><p>Let’s take a look at the constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aef8a7cdc3606bee333edad34f64ef6/href">https://medium.com/media/9aef8a7cdc3606bee333edad34f64ef6/href</a></iframe><blockquote>Most of this code is borrowed from <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/state.ts">state.ts</a></blockquote><p>At first, what is inside the constructor may seem like a lot. Let’s examine what is going on here. You can notice a few <a href="https://rxjs.dev/api/index/class/BehaviorSubject">BehaviorSubjects</a>, a <a href="https://rxjs.dev/api/index/const/queueScheduler">queueScheduler</a> and a <a href="https://rxjs.dev/api/operators/scan">scan</a> operator which is the heart of NgRx Store. I almost missed it at first but <a href="https://medium.com/u/ae97ac398bf9">Alexander Poshtaruk</a> drew my attention to the importance of the Scheduler. This article helped me to understand why we need it and what it does precisely.</p><p><a href="https://blog.cloudboost.io/so-how-does-rx-js-queuescheduler-actually-work-188c1b46526e">So how does Rx.js QueueScheduler actually work?</a></p><p>Basically, it makes sure that dispatched actions are received synchronously i.e. in the order they were initiated. If not used it could potentially introduce a re-entry bug — a situation which causes stack-overflow.</p><p>After that actions$ is combined with reducer$ using <a href="https://rxjs.dev/api/operators/withLatestFrom">withLatestFrom</a>. I believe we need to be aware of reducer$ changes because it could be changed dynamically by calling <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/reducer_manager.ts#L73">ReducerManager#addReducer</a>. I personally never needed this in my application but I decided to keep it in my StoreService implementation just in case.</p><blockquote>It is worth nothing as <a href="https://medium.com/u/802a7996f6b6">Tim Deschryver</a> pointed out addReducer method will be also invoked if StoreModule.forFeature is used.</blockquote><h4>ReducerFactory — connecting the dots</h4><p>I should also mention <em>reducerFactory</em>. I find this piece the hardest to follow in the NgRx Store source. It feels like an endless chain of closures when one tries to debug it.</p><p>It all starts with <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/store_module.ts#L161">createReducerFactory</a> in store_module.ts.</p><blockquote>In my implementation I am omitting the <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/utils.ts#L95">meta reducers</a> handling for the sake of simplicity.</blockquote><p>It will use <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/store_module.ts#L156">combineReducers</a> as a default factory if config does not provide a custom one. This factory will then be invoked in <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/reducer_manager.ts#L35">reducer_manager.ts</a>. Factory will return a reducer combination function which finally is set to be a source of ReducerManager(which is a BehaviorSubject too) and then injected as <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/reducer_manager.ts#L108">ReducerObservable</a> in <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/state.ts#L26">state.ts</a>.</p><p>Here is the <em>reducerFactory</em> I am using — nothing more than a function with a closure which composes the <em>nextState</em> iteratively calling every available application reducer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e29baddf7b4e3e228b0ef43c90888ac3/href">https://medium.com/media/e29baddf7b4e3e228b0ef43c90888ac3/href</a></iframe><h3>Scan operator — the heart and soul of the NgRx Store</h3><p>Now let’s examine what happens after this mixture of actions$ and reducer$ in a form of <a href="https://gist.github.com/evgenyfedorenko/589f67d3b32afbc035d497dd2a02745e#file-store-service-ts-L30">withLatestReducer$</a> piped with a <a href="https://gist.github.com/evgenyfedorenko/589f67d3b32afbc035d497dd2a02745e#file-store-service-ts-L38">scan</a> operator. This is the integral part of NgRx library. It helps to maintain the internal state of the stream. It has two parameters — accumulator function and a seed value. The accumulator has two parameters also — previous state which gets accumulated each time stream is updated and new state value.</p><p>My accumulator is a simple <em>reduceState</em> function. This is where application state gets updated and accumulated on every action dispatch and/or reducer update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fc86225b0e4c92543a96cb507215436/href">https://medium.com/media/2fc86225b0e4c92543a96cb507215436/href</a></iframe><h3>Type Unsafe select and createSelector</h3><p>For the full picture I had to implement <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/store.ts#L126">select</a> and <a href="https://github.com/ngrx/platform/blob/master/modules/store/src/selector.ts#L113">createSelector</a> functions. But without type safety. And by full picture I mean only my own experience with NgRx and how I use it. I am sure there are a lot of things it can do which my StoreService is not capable of. So here is the select function implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35f957d5cba0b19bfeb3e5ebd208a965/href">https://medium.com/media/35f957d5cba0b19bfeb3e5ebd208a965/href</a></iframe><p>It expects a selector as a single param which later in a <em>selectOperator</em> closure will be invoked in a <em>map</em> operator of the <em>state$</em> Observable which is named <em>mapped$</em>.</p><p>At last this is the createSelector implementation which I kept in reducers’ index.ts file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ba438c360e462203dd0598b5aeeb949/href">https://medium.com/media/8ba438c360e462203dd0598b5aeeb949/href</a></iframe><p>I stripped out all the memoization logic from the original source as it is too lengthy and easily can be a subject to another article. Here it is simply separating selectors from a single projector which eventually receives product of all selectors applications.</p><h4>StoreService Usage in a counter test application</h4><p>This is how I am using my store in the app — injecting it in app.component.ts. Then I am selecting the counter in ngOnInit which creates an Observable to be passed in the template along with the async pipe. This way of selecting values from the store differs from the original NgRx implementation. Since I don’t have a Store Observable I subscribe to state$ instead which is returned by invoking the <em>getState method.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b17b171fa174ea2cf1d38cba8569ceb/href">https://medium.com/media/6b17b171fa174ea2cf1d38cba8569ceb/href</a></iframe><p>There are also methods for dispatching the action on increment, decrement and reset buttons’ clicks. All this is pretty standard and aligns with NgRx Store APIs.</p><p><strong>Source Code is on</strong> <a href="https://stackblitz.com/edit/ngrx-seed-jdmgsz">StackBlitz 🧐</a></p><p>Enormous thanks to the following folks for reviewing this article:</p><ul><li><a href="https://medium.com/u/c0dd31a08f42">Santosh Yadav</a></li><li><a href="https://medium.com/u/bd29063a4857">Max Koretskyi</a></li><li><a href="https://medium.com/u/802a7996f6b6">Tim Deschryver</a></li><li><a href="https://medium.com/u/ae97ac398bf9">Alexander Poshtaruk</a></li><li><a href="https://medium.com/u/f7828ad40c7c">Alex Okrushko</a></li></ul><p>For those who are still here with me — thank you for reading it all. I tried to make it easy to follow to the best I could. In case there are any comments or questions feel free to add them here or DM me on twitter <a href="https://twitter.com/e_fedorenko">@e_fedorenko</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe925fe979b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/how-i-wrote-ngrx-store-in-63-lines-of-code-dfe925fe979b">How I wrote NgRx Store in 63 lines of code</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How in-depth knowledge of change detection helped me improve application’s performance]]></title>
            <link>https://medium.com/angular-in-depth/how-in-depth-knowledge-of-change-detection-helped-me-improve-applications-performance-daa04cd56ed6?source=rss-a75caa83b079------2</link>
            <guid isPermaLink="false">https://medium.com/p/daa04cd56ed6</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Evgeny Fedorenko]]></dc:creator>
            <pubDate>Fri, 09 Aug 2019 09:07:36 GMT</pubDate>
            <atom:updated>2020-04-29T20:51:41.341Z</atom:updated>
            <content:encoded><![CDATA[<p>My experience with tuning up Angular application and learning how change detection works under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMmZc19Zt-eip6uT2fvZkg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*-pIPperYQNxz11_0.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>When developing web applications using Angular framework we rarely think about performance implications. Angular is designed to be blazing fast and in general relieves us from performance debugging headaches so we end up losing our grip on “performance first” development practices. As our application grows and we add layers and layers of business logic we may face the degradation of performance metrics and ultimately user experience overall. I will mostly concentrate on runtime performance and my attempts to improve it in a production web application.</p><blockquote><strong>Performance plays a major role in the success of any online venture.</strong></blockquote><blockquote><a href="https://medium.com/@Pinterest_Engineering/driving-user-growth-with-performance-improvements-cfc50dafadd7">Pinterest increased search engine traffic and sign-ups by 15%</a> when they reduced perceived wait times by 40%.</blockquote><h3><strong>A very very busy app</strong></h3><p>Let me explain the problem I was having. The website I am working on now has interactive interface with a lot of requests going back and forth. We use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSockets</a> to receive push updates from other clients which go to broker first and then to browser. Its nature is nothing like a traditional web application you can imagine. It does not have many screens — rather few where one user creates a request and other receives it in real time and acts upon it which results in another update to the request initiator. This process may send the request back and forth a few times and eventually transaction results in the end state.</p><p>Like any other Angular application we have a structure which is considered to be pretty orthodox — 2 modules with its individual routes where each is lazy loaded and each has a tree of components. The component which is causing performance issues is a list built with <a href="https://angular.io/api/common/NgForOf">ngFor</a> directive. Each item in the list contained within the transaction component. Here is the piece of code from list.component.html:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19a8c1f21efeb4ca55c29600d79e199e/href">https://medium.com/media/19a8c1f21efeb4ca55c29600d79e199e/href</a></iframe><p>Each transaction component’s template is essentially a bunch of td containers with some business data: creation date, status, owner id etc. There is two types of statuses —<em> active</em> and <em>completed</em>. Transactions are added to the list dynamically via WebSocket and pushed to the bottom. User either <strong>accepts</strong> the transaction or <strong>rejects</strong> it, then moves on to the next one. Look at these screenshots I have made for you to better understand what I am talking about:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utlt65iBAN-VMIJYcmFTqw.jpeg" /></figure><p>There are two transactions in the list — one <em>completed</em> and one <em>active</em>. User can click <strong>Submit</strong> or <strong>Pass</strong> for accepted or cancelled transaction. This exact action is prone to performance issues when list grows. Consider this screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LqdYBP_xDcMSITGIVrdqw.jpeg" /></figure><p>As you can see list grows and all completed rows are stacked up at the top. Pretty straight forward. Every time user performs an action we change the row’s background color and add some other visual indication that the row becomes inactive(completed). The larger the list — the longer it takes to update the row with appropriate styles. Let’s try to figure out why this is the case…</p><h3>Analyze, then Optimize…</h3><p>When it comes to benchmarking the JavaScript application things get not as clear as it could be. Due to JavaScript’s asynchronous nature performance profiling may be an overwhelming task to deal with. Even though with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/measure">performance.measure</a> Web API’s one can analyze how fast or slow code runs to some extent, but to get a holistic and complete picture is quite an exercise.</p><p>This is when <em>Performance Analyzer</em><strong><em> </em></strong>from Chrome Developer Tools comes in handy. It is <strong>de facto</strong> the most comprehensive and complete instrument for measuring web application’s both network and runtime performance. I won’t lie it took me some time to get around it. The amount of data it spits out is enormous and it may be challenging at first to consume and make sense of it. For instance, I needed to understand what was slowing down the system when the list was growing. So I decided to take some measurements.</p><p>It is also worth noting that the slowdown is hardly noticeable on modern powerful machines like the one I have (2.6 GHz Intel Core i7 16Gb DDR4). One of our clients had an older computer where it was easier to replicate this problem. So for me in order to emulate this environment I needed to throttle CPU power — I made a 6x slowdown. And then I decided to run two sets of tests. I wanted to analyze how long does it take to complete or reject a trade on a list with 1 transaction, 5 transactions and 10 transactions for both real CPU and throttled CPU. I performed 10 tests for each scenario and calculated a mean for each scenario to see the averaged result. Here are the metrics I got:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45963b795e54dad42b10414ce3fb0fdc/href">https://medium.com/media/45963b795e54dad42b10414ce3fb0fdc/href</a></iframe><p>Time in milliseconds is the actual scripting time — indicates how long javascript code runs from the event of user clicking on the button and until the row is updated with appropriate css styles (during this process application makes a REST call to the server, gets a response and paints the row). It is clear (or not?) that the more rows in the table — the longer it takes to process an individual transaction. And the tests were taken with only one active transaction at a time meaning that the rest of them were already in the completed state. <strong><em>So why does it take longer? What is going on here?</em></strong> Let’s review the most interesting parts of the list.component.ts file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e89d23072cb91b5cbbaf160c32d4b72/href">https://medium.com/media/8e89d23072cb91b5cbbaf160c32d4b72/href</a></iframe><p>Ok, turns out there are few things which can be improved about this code. Every experienced Angular developer will point out that ChangeDetectionStrategy should be set to onPush . This technique is well described pretty much in every article about Angular Performance and is fairly easy to implement. If you are not familiar with it please read this great article by <a href="https://medium.com/u/bd29063a4857">Max Koretskyi aka Wizard</a>. It goes in depth of <em>Angular Change Detection Mechanism.</em></p><p><a href="https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f">Everything you need to know about change detection in Angular</a></p><p>All I needed to do is set changeDetection: ChangeDetectionStrategy.onPush in Component decorator. Well, as we know when ChangeDetectionStrategy is set to onPush then component’s will be checked only if its Inputs references are changed (also Event which originates from component or its children will also trigger change detection) therefore if you mutate the Inputs for your components then you will need to change all those instances to be deep copied (copied by value). Check by reference is much faster therefore this is why it improves the overall performance.</p><p>Another improvement which I made was the caching of the getRowClass output. This method is run every time component was checked which is happening on every Change Detection run for every element in the list. I changed it to cache the classes for each row identifier only when any of the rows are changed. Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79a13686a54196b755962cc3a0023ea4/href">https://medium.com/media/79a13686a54196b755962cc3a0023ea4/href</a></iframe><p>Alright, list looks better after these simple modifications. Let’s look at transaction.component.ts now. Again, no onPush detection strategy set — adding that. Another very important behavior worth pointing out — every child component is being checked every time its sibling is updated: this is not desired for rows which are already in the completed state, they are not concerned about any further updates, they should not be running any code inside of them. We may ask why then you keep those rows on the screen, just clear them out — the answer we do have a way to clear those completed rows but users want to keep them on the screen for some time after they are completed for accounting purposes. That is why it is important to optimize the list in the best way possible. There is a solution. Why don’t we disable the change detection for the component once it becomes inactive? <a href="https://angular.io/api/core/ChangeDetectorRef">ChangeDetectionRef</a> class API’s has method detach which <em>detaches</em> component’s view from the change detection tree so that next time if parent component triggers change detection it won’t affect this child component. Let’s look at the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/850e260f6280621ee6b832b3ea764e1c/href">https://medium.com/media/850e260f6280621ee6b832b3ea764e1c/href</a></iframe><p>Ok, we are moving in the right direction. After this round of changes I ran the performance tests again and here were the results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02945bdca047b48a25332bcc55f3301a/href">https://medium.com/media/02945bdca047b48a25332bcc55f3301a/href</a></iframe><p>Alright, now tests run almost twice as fast — this is a significant improvement. But we can do better. I want to go over <a href="https://angular.io/api/common/NgForOf">ngFor</a> directive in order to determine how we can improve its performance. We know that this directive helps us to build collections. We place it on the container which becomes a parent for cloned templates ngFor creates for every element in the collection. This directive runs a check using <a href="https://angular.io/api/core/IterableDiffer">IterableDiffer</a> interface to identify the changes in the collection between the change detection runs. The result of it is an object of <a href="https://angular.io/api/core/IterableChanges">IterableChanges</a> which then are applied to update the view. For a much deeper dive in ngFor internals read this <a href="https://blog.mgechev.com/2017/11/14/angular-iterablediffer-keyvaluediffer-custom-differ-track-by-fn-performance/">great article</a>.</p><p>What I am trying to say is next: we should not run a Differ on a list with items which never change. Our completed rows are evaluated every change detection run which is inefficient. The solution would be to move all these rows out of the main collection so that only active transactions are being evaluated for possible changes. As a result I moved all completed transactions to another completedTransactions array and looped over it in the template just the same way using ngFor . After this step I ran the performance tests again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbc0fec600e6fb5cc24e4f331183e76f/href">https://medium.com/media/dbc0fec600e6fb5cc24e4f331183e76f/href</a></iframe><p>Finally! It <em>does not matter</em> anymore how big is the collection. It takes the same time to process an update on one active transaction and the list of 10 transactions with 9 of them being inactive which logically makes sense. (83ms on throttled CPU for 1 row and 85ms for 10 rows). This is much much better.</p><h3>Just to sum up here is the list of changes we performed:</h3><ul><li>updated change detection strategy to onPush for both parent and child components;</li><li>cached the most expensive methods for child components so we don’t recalculate the unchanged output every change detection run;</li><li>disabled change detection for the elements which don’t change anymore;</li><li>moved all completed elements to another collection so that ngFor internally runs faster.</li></ul><h3>Other potential improvements?</h3><p>I personally did not try to implement this but <a href="https://material.angular.io/cdk/scrolling/overview">virtual scrolling</a> in my opinion is worth the shot. In a nutshell it is a way to reduce the number of rows on user’s viewport which in result improves performance: less rows -&gt; more performant application.</p><p>Another improvement would be to move all housekeeping logic to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Web Workers</a> — staff like server logging, Web Socket heartbeats etc. Great article about using Web Workers can be found here — <a href="https://blog.angularindepth.com/improve-performance-with-web-workers-497931fdef1b">Improve Performance with Web Workers</a>.</p><p><strong><em>This is it. Thank you for reading. If you liked this article please follow me on </em></strong><a href="https://twitter.com/e_fedorenko"><strong><em>Twitter</em></strong></a><strong><em> to get updates.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daa04cd56ed6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/how-in-depth-knowledge-of-change-detection-helped-me-improve-applications-performance-daa04cd56ed6">How in-depth knowledge of change detection helped me improve application’s performance</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>