Determine the appropriate value either through key retrieval or conditional statements

My goal is to enhance the efficiency of a slider that contains numerous conditional statements triggered during sliding/swiping actions.

Which approach yields better performance?

1- Utilizing a predefined object with key conditions

const controller = (config) => {
    top: {
      positionVertical: false,
      orderAfter: false,
      width: '100%',
      height: config.height + 'px',
    },
    bottom: {
      positionVertical: false,
      orderAfter: true,
      width: '100%',
      height: config.height + 'px',
    },
    left: {
      positionVertical: true,
      orderAfter: false,
      width: config.width + 'px',
      height: '100%'
    },
    right: {
      positionVertical: true,
      orderAfter: true,
      width: config.width + 'px',
      height: '100%'
    }
};

this.gallery.sub$.pipe(
  map(({state, config}) => this.controller(config)[config.position])
);

2- Implementing standard if-else or switch case statements

this.gallery.sub$.pipe(
  map(({state, config}) => {
    switch(config.position) {
       case 'top': return {
         positionVertical: false,
         orderAfter: false,
         width: '100%',
         height: config.height + 'px',
       }
       case 'left': return {
         positionVertical: true,
         orderAfter: false,
         width: config.width + 'px',
         height: '100%'
       }
       case 'right': return {
         positionVertical: true,
         orderAfter: true,
         width: config.width + 'px',
         height: '100%'
       }
       default: return {
         positionVertical: false,
         orderAfter: true,
         width: '100%',
         height: config.height + 'px',
      }
    }
  })
);

Your insights and additional explanations are encouraged.

Answer №1

When comparing the two versions of the code, it's highly unlikely that you will notice any performance variance. According to the test results conducted by Yuan, even with 10,000 entries in your slider, there should not be any significant difference. Although these tests were probably done on a desktop CPU, it is safe to assume that the impact on a mobile CPU would also be minimal.

However, based on fundamental principles, it is easy to infer which version is faster - the second one, simply because it undertakes less work. Yuan's tests confirm this conclusion, particularly evident in extreme scenarios like 10,000,000 entries (although the specifics of the test setup are not provided).

Let's delve deeper into why the second version is the more efficient option. If we examine the first version, it follows a multi-step process for each entry:

  1. It calculates values for all four cases and generates an object for each case.
  2. It constructs a new master object containing all four of these inner objects.
  3. It selects one of the inner objects based on the config.position and disregards the rest.

In contrast, the second version simplifies this process:

  1. It uses config.position to determine which type of object to create out of the four possibilities.
  2. It constructs only the selected object and ignores the other three types.
  3. There is no third step required.

It is logical to presume that the task of calculating and constructing four distinct objects, along with a container object to encapsulate them, will take longer than the operations involved in calculating and constructing just one of those objects.

From a stylistic perspective, a minor adjustment could be made to enhance the second version. The default: case could be modified to case 'bottom': to align with the other cases and improve clarity of intention.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The test is failing to execute the service mock promise due to an issue with the `

A problem has arisen while creating a mock for the BoardService. It appears that the .then function is not executing in the controller during testing, even though it works perfectly fine in the live application. Below is the test snippet: beforeEach(inje ...

Encountered an Unpredictable SyntaxError: Is this a Cross-Domain Problem?

I have been attempting to connect with the Indian Railway API using Ajax in order to retrieve data in JSON format. Below is the code I am using: <!DOCTYPE> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleap ...

Encountering a Typescript error while attempting to utilize mongoose functions

An example of a User interface is shown below: import {Document} from "mongoose"; export interface IUser extends Document{ email: string; password: string; strategy: string; userId: string; isValidPassword(password: string): ...

Is there a way to redirect the user to a different page without refreshing the page during navigation?

Utilizing javascript, ajax, and jquery to dynamically load content from PHP files without refreshing the page has been a successful venture. However, I am facing a challenge in creating a hyperlink within one of the loaded contents that redirects the user ...

Unable to retrieve the iframe variable from the parent as it returns undefined

I am trying to retrieve a variable within an iframe from the parent index.html. Here is the index.html code: <!doctype html> <html lang="en-us> <head> <title>Test</title> </head> <body> <p>Test& ...

The onclick button in React is not triggering

I am currently working on a component that processes card clicks and redirects users to a previous route, however, the OnClick function does not seem to be functioning properly. I'm trying to pinpoint where I might be going wrong. function Character ...

retrieving the smallest and largest values from a date range selector

I have been implementing a date range slider following the guidelines from this resource. I successfully set up the slider according to the documentation, but now I need to retrieve the minimum and maximum values as the slider is being moved. I attempted t ...

Submitting the form without utilizing Ajax, but instead sending data directly to a PHP script

I've encountered an issue while posting a form to a PHP file using AJAX. Despite my efforts, the form is bypassing AJAX and posting directly to the PHP file. Here is my form: <form id="editform" name="editform" action="ajaxeditform.php" method= ...

Converting a C# Dictionary<string,string> to a TypeScript Map<string,string>

Struggling to find the best approach for handling key:value pairs in TypeScript when receiving a dictionary object from the C# backend. Everything attempted so far has not yielded the expected results. This is the C# code snippet: var displayFields = ...

What strategies can I implement to prevent position: absolute from obscuring my content?

I am currently experiencing an issue with my Google Map loading within a tab. The container div has the position set to absolute. Although the map displays correctly, I am encountering a problem where it covers any content I try to place underneath it. My ...

Having trouble accessing properties within a JavaScript object array in React.js?

I have a React.js component that fetches its initial state data from an API call in the componentDidMount(). This data comprises an array of objects. While I can see the entire array and individual elements using JSON.stringify (for debugging purposes), a ...

Tips for enhancing the TypeScript definition of Material UI 3 theme by integrating the Material UI pickers theme

Trying to enhance the Material-UI theme with the Typescript typings of Material-UI-Pickers for the latest versions listed here: "@material-ui/core": "^3.9.2", "material-ui-pickers": "^2.2.1", A note on the bottom of the Material UI picker page mentions t ...

File uploading using JQuery and AJAX

An error occurred: Cannot read property 'length' of undefined I'm facing an issue with 3 file fields and their upload buttons. The problem lies in the fact that the file field is being returned as undefined. Here is the JavaScript code: $ ...

The Year as a Reference Point

I came across an interesting issue while working with dictionaries and JSON in sessionStorage. Initially, I had a dictionary structured like this: "name" : { "2016" : { "1" : "info" } } After successfully adding it to sessionS ...

Integrate JQuery-Ui into an Angular 7 application using an external .js file

I'm currently working on an Angular 7 project and facing some challenges while trying to integrate the JQuery-Ui plugin. I have successfully installed both JQuery and the plugin, and added them to the scripts array in my angular.json file. Even though ...

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

Remove Chosen Pictures (Checkbox/PHP/MySQL)

I am currently displaying images from a Database using the following HTML code: <li> <input type="checkbox" id="1" /> <a rel="gallery_group" href="images/big/1.jpg" title="Image 1"> <img src="images/small/1.jpg" alt="" ...

Javascript is not functioning properly when making an ajax call

Having a bit of trouble with JavaScript not working after an Ajax call. Everything functions normally until new data is fetched from the database or an Ajax call is made. The issue seems to be that the JavaScript doesn't load properly. Any help would ...

Using JSON Filtering with React

I am currently working on fetching JSON data and implementing a filtering feature for the displayed content. An error that I am encountering is: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined Any insights on what might be ...

How to Use JQuery to Display Elements with a Vague Name?

Several PHP-generated divs are structured as follows: <div style="width:215px;height:305px;background-color: rgba(255, 255, 255, 0.5);background-position: 0px 0px;background-repeat: no-repeat;background-size: 215px 305px;display:none;position:fixed;top ...