When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking?

I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memory and speed.

Here are the different methods I have been considering:

class MyClass {
  readonly functionA = (v: string | number, maxDeep: number, curDeep: number = 0): string => {
      if (curDeep < maxDeep) {
          return this.functionA(v, maxDeep, curDeep + 1);
      } else {
          return "function A" + v;
      }
  }

  static functionB(v: string | number, maxDeep: number, curDeep: number = 0): string {
      if (curDeep < maxDeep) {
          return MyClass.functionB(v, maxDeep, curDeep + 1);
      } else {
          return "function B" + v;
      }
  }

  functionC(v: string | number, maxDeep: number, curDeep: number = 0): string {
      if (curDeep < maxDeep) {
          return this.functionC(v, maxDeep, curDeep + 1);
      } else {
          return "function C" + v;
      }
  }

  static readonly functionD = (v: string | number, maxDeep: number, curDeep: number = 0): string => {
      if (curDeep < maxDeep) {
          return MyClass.functionD(v, maxDeep, curDeep + 1);
      } else {
          return "function D" + v;
      }
  }
}

I attempted to use JSBen to compare the difference, but the results appeared to be inconsistent. https://i.sstatic.net/rc8Pw.png

Answer β„–1

If the concern for performance optimization is at such a granular level, then including a class with only static methods can introduce unnecessary overhead. Classes are typically meant to be instantiated, and not utilizing this feature leads to wastage of computational resources.

Upon testing your examples on MacOS using Chrome 90.0.4430.93, the results showed:

https://i.sstatic.net/1cd2S.png

The performance costs of static methods were significantly higher compared to instance methods which are guaranteed to be faster. This could possibly be attributed to classes being designed for instantiation.


A simpler alternative would be using a simple object. Consider incorporating these two tests:

const obj = {
  functionE(v, maxDeep, curDeep = 0) {
    //...
  },

  functionF: (v, maxDeep, curDeep = 0) => {
    //...
  }
};

https://i.sstatic.net/9yZ3K.png

These perform nearly as well as instance methods and follow a more logical pattern. Without the need for classes, there is no instantiation required.


Alternatively, an even simpler approach can be taken:

function rawFunctionStatementG(v, maxDeep, curDeep = 0) {
  //...
}

const rawFunctionVarH = (v, maxDeep, curDeep = 0) => {
  //...
};

https://i.sstatic.net/Q5aVO.png

In terms of performance, this method stands out due to direct reference to the function without needing to look it up in an object.

Updated jsben.ch


Furthermore, from a tree shaking perspective, this format proves to be the most efficient. Bundlers find it easier to manage whole exported values rather than handling individual objects separately.

If you structure your code like this:

// util-fns.ts
export function myFuncA() { /* ... */ }
export function myFuncB() { /* ... */ }

// some consumer file
import { myFuncA } from './util-fns'

It becomes simple for a bundler to identify unused functions like myFuncB and potentially remove them during bundling.


To conclude...

β€œThe real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.” – Donald Knuth

In the vast majority of JavaScript applications, performance optimizations at such a micro-level may not have significant impact. It's essential to prioritize data structures that align with the application's requirements and adhere to the established standards within the codebase/organization.

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

Using VueJS: accessing this.$store within component data property

I am interested in utilizing the data from my Vuex store in both my app and template. My Vuex store: var Vue = require('vue'); var Vuex = require('vuex'); Vue.use(Vuex) let store = new Vuex.Store({ state: { user: ...

passport not initializing session with requests

I am currently utilizing passportJS for managing login and persistent sessions on the server backend. While everything functions properly when sending requests from the server frontend (a webpage that I didn't create and lack sufficient knowledge to ...

The inner nested ng-repeat section is not properly binding to the scope variable and appears to be commented out

In my code, there is a nested ng-repeat set up. The 'boards' variable in the scope is an array that contains another array called 'tasks', which also consists of arrays. In the innermost ng-repeat, I am attempting to bind to task.conten ...

TypeScript in Angular causing lodash tree shaking failure

I am currently working on a large project that involves TypeScript. Various attempts have been made to optimize the use of lodash in my project. Before making any conclusions, I believe it is important to review the outcomes of my efforts. The command I ...

Handling AJAX requests using jQuery

I'm currently in the process of learning how to utilize jQuery Ajax. Could you explain to me the significance of function(response), as well as what exactly is meant by response == 1 and response == 2? jQuery.post(ajaxurl, data, function(response) { ...

Leveraging Ajax and jQuery to create a POST request for adding a new record to a MySQL table within a Node.js server

My form is designed to collect user information like name, age, and more. The aim is to submit this data from the client side, inserting it into a MySQL table row. However, I'm facing difficulties in getting the data to successfully insert. Below are ...

How do I prevent my image slider from scrolling to the top of the page when I click next or prev?

<script> export default { name: "ImageSlider", data() { return { images: [ "https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg", "https://cdn.pixabay.com/photo/2016/02/17/2 ...

What is the best way to update a value and trigger a re-render in ReactJS?

this.state={ value: 'v1', newValue: '', } componentDidMount = () => { let nV = this.state.value + 'received'; this.setState({ newValue: nV, }); } tabClick = (val) => { this.setState({ value: val, ...

Tips for invoking C language code from JavaScript by using the js-ctypes extension in Firefox

I need assistance with developing a Firefox extension that requires calling native C code. Here is my C program code: #include<windows.h> int add(int a, int b) { return(a + b); } And here is my JavaScript code: var {Cu} = require('chrome ...

Is it possible to modify a prop in a functional component?

I am working on a functional component that has the following structure: export const Navbarr = ({items}) => { const [user, error] = useAuthState(auth); const [cartItems, setCartItems] = React.useState(0); const fetchUserCartItems = async() =&g ...

Crafting a robust and secure password using Yup and Formik while receiving personalized error notifications

My Password Validation Dilemma I'm in the process of developing a password field that can assess the strength of the input provided. In a different response, I came across a regex that I could utilize to validate whether the input meets specific crit ...

The efficiency of Testing Library findBy* queries is optimized when utilized alongside async/await functionality

After reviewing the documentation, it was noted that queries made using findBy return a Promise. Interestingly, utilizing these queries with Promise.prototype.catch() seems ineffective in comparison to pairing them with async/await + try...catch. An insta ...

What is preventing my counter from functioning when I click on the canvas?

I am attempting to increment the count every time a bouncing ball in the browser is clicked using this.setState({count: this.state.count + 1});. I thought my code was correct since I have done similar tasks before without using canvas, but it's not fu ...

The fetch request in a React application is not returning a response body, whereas the same request functions properly when made using Postman

My React app is successfully running locally with backend REST APIs also running locally. However, when I attempt to make a POST call to the REST API, the call goes through but the body appears to be empty. Below is a snippet of the sample code: const bod ...

How can I exclude the last parameter from a function type in Typescript?

If I have a function type like this: type FunctionType = (a: number, b: string, c: boolean) => void How can I create a new type with the last parameter removed? type NewFunctionType = OmitLastParameter<FunctionType> Desired type for NewFunctionT ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

What is the best way to refresh updated .js files directly from the browser console?

Is it possible to use RequireJS 2 to dynamically reload a recently updated .js file? Let me explain my scenario: I have a Backbone.js object named Foo with a function called Bar that currently displays an alert with "abc" when called; In my webpage, I ex ...

Navigate to the specified URL once the Ajax function has completed successfully

I'm having trouble with opening a URL from an Ajax function. It seems like the URL is not being called. This is the code I am using: $(document).on( "click",".btndriver", function() { var id = $(this).attr("id"); var nombre = $(this).att ...

eliminating reliance on promises

I understand the importance of promises, however I am faced with a challenge as I have multiple old functions that currently operate synchronously: function getSomething() { return someExternalLibrary.functionReturnsAValue() } console.log(getSomething( ...

Is it possible to create multiple text input components using the "each" function, and how can I update the state by combining all of them together?

I am looking to create a text-based word game where the length of each word changes with every level. Each letter will be placed in its own box, forming a matrix (e.g. 10 words, length: 10 => 10x10 matrix). How can I generate multiple text input compone ...