Skip to content

Instantly share code, notes, and snippets.

@sasknot
Last active April 13, 2023 15:01
Show Gist options
  • Save sasknot/f43f271eb81440d9e2500a9c3e34c36c to your computer and use it in GitHub Desktop.
Save sasknot/f43f271eb81440d9e2500a9c3e34c36c to your computer and use it in GitHub Desktop.
JavaScript benchmark example
const arr = ['love', 'lovec', 'wlovec', 'asdlov123', 'abc123']
const word = 'love'
for (const curWord of arr) {
if (word.split('').every((letter) => curWord.includes(letter))) {
console.log('1', curWord)
}
}
for (const curWord of arr) {
let yes = true
for (const letter of word) {
if (!curWord.includes(letter)) {
yes = false
break
}
}
if (yes) {
console.log('2', curWord)
}
}
for (const curWord of arr) {
let i
for (i = 0; i < word.length; i++) {
if (!curWord.includes(word.at(i))) {
break
}
}
if (i === word.length) {
console.log('3', curWord)
}
}
for (let j = 0; j < arr.length; j++) {
let i;
for (i = 0; i < word.length; i++) {
if (!arr[j].includes(word.at(i))) {
break
}
}
if (i === word.length) {
console.log('4', arr[j])
}
}
loop1:
for (const curWord of arr) {
for (const letter of word) {
if (!curWord.includes(letter)) {
break loop1
}
}
console.log('5', curWord)
}
loop1:
for (const curWord of arr) {
for (let i = 0; i < word.length; i++) {
if (!curWord.includes(word.at(i))) {
break loop1
}
}
console.log('6', curWord)
}
loop1:
for (let j = 0; j < arr.length; j++) {
for (let i = 0; i < word.length; i++) {
if (!arr[j].includes(word.at(i))) {
break loop1
}
}
console.log('7', arr[j])
}
@sasknot
Copy link
Author

sasknot commented Apr 13, 2023

Test cases results

  • case1: 88K ops/s ± 0.65% | 2.68 % slower
  • case2: 86K ops/s ± 0.39% | 4.87 % slower
  • case3: 86K ops/s ± 0.68% | 4.11 % slower
  • case4: 90K ops/s ± 0.44% | Fastest
  • case5: 83K ops/s ± 0.36% | 7.9 % slower
  • case6: 84K ops/s ± 0.35% | 6.86 % slower
  • case7: 90K ops/s ± 0.37% | Fastest

Conclusion

The lesser number of variables or functions, more faster our code will be.
Relying in simple structures like basic for and if is more performant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment