GUIDES Optimizing Embedded JavaScript Defining Class Methods
About
Binary Data
Index
Convert String to ArrayBuffer
Convert ArrayBuffer to String
Convert ArrayBuffers to String
Handle Errors Converting ArrayBuffer to String
Immutable ArrayBuffers
Resize an ArrayBuffer
Combine ArrayBuffers
Convert Base64 to Binary Data
Convert Binary Data to Base64
Convert Binary Data to Hex
Convert Hex to Binary Data
Calculate CRC for Binary Data
Compress Binary Data – One Buffer
Compress Binary Data – Streaming
Decompress Binary Data – One Buffer
Decompress Binary Data – Streaming
Callbacks
Index
One-Time Callback
Repeating Callback
Repeating Callback with Initial Delay
Immediate Callback
Reschedule Callback
Cancel Callback
Suspend Callback
What About setTimeout?
Optimizing Embedded JavaScript
Index
When to Optimize
Know Where to Optimize
Looping through an Array
Iterating Over a String
Building a String
Avoid Copying Buffers
Accessing Properties
Map versus Object
Appending to an Array
Operating on Bits
Defining Class Methods
Reducing Stack Use
Time
Index
Get Unix Time
Get Time of Day
Get Date
Get Time Since System Start
Get Microseconds
Set System Date and Time
Set Real-Time Clock Time
Get Time and Date from Network
Get Time and Date from Real-Time Clock
Sleep

Defining Class Methods

Arrow functions are a popular tool for JavaScript developers. Not only do they solve the vexing this binding challenge, but they do so using a concise syntax. As a result, developers sometimes use arrow functions where there is a more efficient alternative.

One particularly ill-advised place to use arrow functions is in defining the methods of a class. Using arrow functions here puts the methods on each instance of Example. If there are 10 instances of Example, that's 30 unnecessary function instances taking up RAM. Those unnecessary function instances are created when the class is instantiated, so they take additional time to execution.

Using the standard class syntax instead puts the functions on the prototype of Example so they are shared by all instances.

/* BEFORE */
class Example {
	begin = options => {
		// code here
	}
	send = buffer => {
		// code here
	}
	end = () => {
		// code here
	}
}

/* AFTER */
class Example {
	begin(options) {
		// code here
	}
	send(buffer) {
		// code here
	}
	end() {
		// code here
	}
}