02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School

Avoiding Conditions in JavaScript for Better Performance

Avoiding Conditions in JavaScript for Better Performance

Optimizing your JavaScript code often involves reducing the use of complex conditions and loops, which can hinder performance. This tutorial explores strategies for simplifying logic using ES6 features like maps and object references and includes a note on modern approaches like React Hooks in 2024.


Key Concepts

  1. Why Avoid Conditions?

    • Repeated conditions and loops add complexity and can degrade performance.
    • Simplifying or replacing them improves efficiency and reduces runtime overhead.
  2. Leveraging ES6 Maps

    • Maps in ES6 allow for efficient key-value pair storage.
    • Unlike objects, map keys can be of any type, including functions and objects.
    • Example:
      const itemTypeMap = new Map();
      itemTypeMap.set('navLink', []);
      itemTypeMap.set('navBrand', []);
      
  3. Replacing Switch Statements

    • A switch with multiple cases can be replaced with a map for better readability and performance.
    • Example:
      const renderMap = new Map([
          ['navLink', () => renderNavLink()],
          ['navBrand', () => renderNavBrand()],
      ]);
      
      const renderItem = renderMap.get(itemType);
      if (renderItem) renderItem();
      
  4. Minimizing Loop Complexity

    • Extract reusable logic outside loops to avoid redundant computation.
    • Example:
      for (const child of children) {
          const renderer = itemTypeMap.get(child.type);
          if (renderer) renderer(child);
      }
      
  5. Using Constructors for Predefined Logic

    • Move static or rarely-changing logic to the constructor for better performance during rendering.
    • Example:
      constructor(props) {
          super(props);
          this.itemTypeMap = new Map([
              ['navLink', 'someValue'],
              ['navBrand', 'anotherValue'],
          ]);
      }
      

React Hooks and Performance in 2024

In modern React development, hooks have become essential for managing state and side effects while improving performance. Hooks like useMemo and useCallback are particularly useful for reducing re-renders and optimizing expensive computations:

  • useMemo: Memoizes a computed value, ensuring it is only recalculated when dependencies change.

    const computedValue = useMemo(() => heavyComputation(input), [input]);
    
  • useCallback: Memoizes a function reference, ensuring it is only recreated when dependencies change, which is helpful when passing callbacks to child components.

    const handleClick = useCallback(() => doSomething(value), [value]);
    
  • Why Use Hooks?
    React Hooks reduce boilerplate code, improve readability, and allow functional components to manage performance-critical logic effectively. When paired with strategies like avoiding conditions, they can make your application faster and easier to maintain.


Practical Example

Before Optimization:

switch (itemType) {
    case 'navLink':
        renderNavLink();
        break;
    case 'navBrand':
        renderNavBrand();
        break;
    default:
        renderDefault();
}

After Optimization:

const itemTypeMap = new Map([
    ['navLink', renderNavLink],
    ['navBrand', renderNavBrand],
]);

const renderItem = itemTypeMap.get(itemType) || renderDefault;
renderItem();

Using React Hooks:

const renderItem = useMemo(() => itemTypeMap.get(itemType) || renderDefault, [itemType]);
renderItem();

Why Optimize?

Combining ES6 features like maps and React Hooks in 2024 provides a powerful toolkit for creating highly performant and maintainable applications. By reducing complexity, memoizing computations, and avoiding unnecessary re-renders, you can ensure your app remains responsive and efficient.

Explore more on React optimization and performance best practices at 02Geek React Performance Enhancements.

Video Transcript

00:00When I think about optimization,
00:02the first thing in my mind
00:04that comes is overusing conditions and loops.
00:08In this lecture, I'm gonna go ahead
00:10and show you how do you extract out from loops
00:13and from conditions, some of the building logic
00:16to reduce the complexity of your loops.
00:18By reducing the complexity,
00:20you're automatically gonna improve your performance.
00:22And this applies in any area if it's
00:25the server or the client.
00:26By extracting out things that are constant,
00:29extracting out things that don't need to be redefined
00:31or applied or configured,
00:33you're gonna automatically reduce a lot
00:35of your operations complexities.
00:37So let's go ahead and start looking at
00:40how do we think about this?
00:41And by the way, this applies also to timers
00:43or things that relate to time and loops
00:45'cause it's a similar topic.
00:46And we're gonna take a look at how do we simplify
00:49conditions, sometimes even getting rid of them completely.
00:51But in our case, we're gonna simplify them
00:53with the use of a map.
00:54But it also applies to the usage of objects in a scenario
00:58where your key could be a string.
01:00So let's jump right into it.
01:01Let's see what I mean by
01:02how we reduce complexity of conditions.
01:07Although in our case, our switch is really
01:09our best condition here.
01:10Generally speaking, anytime you could avoid a condition,
01:13it's a good thing, especially if it's something
01:16that is happening often in our case,
01:18our render would not be called that often.
01:20So it doesn't really matter that much that we have a switch.
01:24Although imagine that in our children we had here 300
01:27children and in the case of 300 children, we have a lot
01:30of conditions and a lot of logic through to go through.
01:33Imagine there's 10 different types of items
01:36and we have 10 different switches.
01:37This is a mess. Let me show you a better way in that case.
01:41And it's really very specific,
01:43these enhancements are very specific to scenarios
01:46where they're appro app app applicable.
01:48And in this situation we're talking about a new feature in
01:51ES six because of our usage
01:54of classes here to reference things.
01:57Now technically speaking, you could do this oso
01:59with object references.
02:01And I'm gonna show you first this new way of doing it
02:03with maps, which is uh uh a new feature, new maps,
02:07now a new feature to ES six.
02:09Now the idea of a map is basically to tie between a key
02:13and a value just like you would have in a regular string
02:16where you have a key
02:17and then you have a value
02:19by assigning this key value condition.
02:21These are perfect for situations such as a switch.
02:24What we're actually doing is we're basically creating a
02:27linkage between the two.
02:28Now you could have done this with an object if the key was a
02:30string or a number.
02:32In our case, our key,
02:34because we're using a map,
02:35our key is gonna be basically a class, so, or an object.
02:39So it's gonna be a complex element
02:40and the value itself will set here the value
02:43to be the actual um, item here.
02:45So nav items is the value.
02:47Lemme just go ahead and copy this two times
02:50because in our case this is not the most effective probably
02:53in this scenario because we only have two cases.
02:55But if we had multiple cases or this item was called
02:58A lot of times this could have become incredibly useful.
03:02Now beyond that, our definition here inside
03:05of our render means that every single time it needs
03:07to be created and even better enhancement,
03:10especially if this render method is gonna be called
03:12multiple times, is to create a constructor.
03:16Lemme just double check that I'm typing
03:17constructor correctly.
03:19Let me find one item.
03:20I believe a button no buttons don't have.
03:23All right, we'll have to create it.
03:24Alright, so construct tour and it accepts props.
03:29And let me just go ahead here and just call super
03:34and send those props over so they can,
03:36everything will continue working.
03:38But let's continue in the process.
03:39So I'm creating these map, I'm creating these linkages.
03:42Now if our render would call be called a hundred times a
03:45second, this would actually be a lot of work as well.
03:47Maybe more so than this loop
03:49or maybe it would we still need to enhance even further.
03:52Now lemme go ahead here and I'm just gonna go ahead
03:54and comment out all of this switch.
03:57And instead of that I'll have your one simple if condition
04:00and this if condition.
04:01We'll basically check to see if our map has a reference
04:04to our item type.
04:07If it does, then good, then we have a reference in the case
04:09that we have a reference.
04:10Let's go ahead here and assign our value
04:15and we're gonna assign our value to be a push to the item.
04:19Now again, if we're talking about enhancement improvements,
04:22another thing that we could do is first
04:23of all define another, another let,
04:26so I could define your another let and then use that item
04:29'cause the sled is only applicable within this for loop
04:32and then I would AP applicably define it.
04:34But in this case, let me just, let me just continue here.
04:36And L two are and Ls.
04:38And for our LS condition I'm just gonna go
04:40and set that other, so if our item didn't exist in,
04:43in the mapping, then only then we would actually run it.
04:46And now the other situation use the then the other. Sorry.
04:51So with that said, let's go ahead
04:52and note to move this constant definition, we will,
04:55we'll change it into be a this um, class mapping.
04:59And our class mapping is literally going
05:02to equal that new map.
05:05And then I could just go ahead and map these classes
05:08because we need references to these classes.
05:11Although technically we wouldn't have yet our children
05:14and our brands, although
05:15what we could do is literally just go ahead
05:18and create them, uh,
05:19already explicitly in our definition of our class.
05:22So what I could do here is just go ahead here
05:24and just move this right into this.
05:28And again, we're talking about performance.
05:29There's so many small things that you could do
05:31to improve performance.
05:32So in this case, I'm just gonna go ahead
05:34and create an array as soon
05:35as we're creating the constructor.
05:36And again, a very important part of this is making sure
05:39that you only do this
05:41if it's gonna improve your performance.
05:42Really depends on a lot of moving fa factors.
05:45So one is another thing
05:47'cause I'm using three times the definition.
05:49Let me just go ahead here and create a cons, call it map.
05:53And I'm just gonna go ahead and create a new map instead
05:55of creating the this here
05:56And then assign our map to be our class mapping.
06:01And lemme just go ahead and move this up here
06:05and we could delete that.
06:07And all these small things they gather up together.
06:09So all these small things that you're doing is
06:11improving your performance.
06:12Beautiful. So now
06:14that I've created this mapping class class,
06:16I could literally take this constant
06:18and just assign it back in there and I could go ahead
06:22and also continue down this path.
06:24If we're already doing this, I could go ahead
06:26and in my mapping process,
06:29after I created the map, I could then go ahead
06:33and refer to the nav link to get access
06:36to my brands, for example.
06:38So I could go to my mav nav link to just assign that value
06:42to get a local reference
06:44and assign the item to get a local, well first of all,
06:47this is the one that should be here
06:49and this is the one that should be here.
06:50And sometimes more typing is involved
06:52with creating something that is just a little bit
06:55better in performance.
06:56Should we create a global variable? Probably not.
06:59So really in, in, in, in true essence,
07:02we really don't want a global variable
07:04because we don't want every time things are rendering
07:06to use the same variable.
07:09So for our case, I'm not gonna go
07:10ahead and do all this craziness.
07:11Okay? So I'm just gonna delete that
07:13and I'm gonna, uh, lemme just undo, undo,
07:15undo, go back to where we were.
07:17But that's exactly what you would do if you wanted
07:19to be in a scenario where you're improving your
07:21performance even more.
07:22So in certain situations.
07:24In our case, we would have
07:25to instantiate a new variable each time.
07:27So probably this would be an overkill.
07:30So let me just delete, delete, delete.
07:32Let me just, I don't need that. Okay, so we don't need that.
07:35And in our Ls, let's put our Ls back in there
07:38and we'll go to our other
07:42push item.
07:43And really why did I do it differently?
07:45Mainly because we need
07:47to instantiate a new array every time.
07:49'cause we need them for our filtering.
07:51So moving it out wouldn't make a lot of sense
07:53'cause we have to instantiate them anyway,
07:55so there's no help in actually creating it in advance.
07:58Although if we could create the map in advance,
08:00that would be wicked, but we can't
08:01because we need access to the actual linkage of the items
08:04that we're creating only in this render method.
08:07So these steps are mandatory for us.
08:09So if I go ahead and save this
08:10and I, we went through a lot of steps here
08:12and really they just show you how complex performance is
08:15as it relates to specific situations
08:17where if I had your a hundred items,
08:19you'd have a different performance
08:20than if I had only two items.
08:22If this item has been rendered a hundred times a second,
08:24we would a second, we would have different render,
08:26different performance issues.
08:28And if we would be rendering this, for example,
08:30if we had some sort of logic that was living on a server
08:33and there's let's say multiple types of users
08:35that are coming in and we need
08:37to give them the right information using an if condition is
08:40probably the least effective mechanism.
08:42Create keys in the way such as maps are more efficient.
08:46And generally speaking, if we're on a server we could use
08:48just a, a classic key value combination to
08:51and anytime we want to improve performance.
08:53But again, a lot of times when
08:54You do that it hinders on readability of code
08:57'cause this is a lot less readable.
08:59But sometimes these type
09:00of enhancements are gonna create a much better experience
09:03for your overall performance of your application.
09:06Okay, so that's it about performance and, and
09:09and really big picture performance ES six topics
09:14inside of React and JavaScript in general in this lecture.
09:18I hope it opened up a whole world for you in the world
09:21of reducing complexities of your conditions and loops.
09:25In the next lecture and the wrap up of this section,
09:28we're gonna move into React
09:29and we're gonna take a look at the overall benefit
09:31of actually working with the React in compared to not to,
09:35and it as it applies to the DOM itself.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!