toCamelCase performance test

Benchmark created on


Setup

let str = "This is an Example-String!";

function toCamelCase1(str) {
  // replace all non-alphanumeric characters with space
  str = str.replace(/[^a-zA-Z0-9]/g, ' ');
  
  // convert the first letter of each word to uppercase
  str = str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(word, index) {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, ''); // remove all spaces

  return str;
}

function toCamelCase2(str) {
  let words = str.split(/[^a-zA-Z0-9]/); // split the string into an array of words
  let camelCaseStr = words[0].toLowerCase(); // convert the first word to lowercase

  // convert the first letter of each subsequent word to uppercase and append to the camel case string
  for (let i = 1; i < words.length; i++) {
    let capitalizedWord = words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase();
    camelCaseStr += capitalizedWord;
  }

  return camelCaseStr;
}

function toCamelCase3(str) {
  let words = str.split(/[^a-zA-Z0-9]/); // split the string into an array of words
  let camelCaseArr = [words[0].toLowerCase()]; // convert the first word to lowercase and add it to the array

  // convert the first letter of each subsequent word to uppercase and add it to the array
  for (let i = 1; i < words.length; i++) {
    let capitalizedWord = words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase();
    camelCaseArr.push(capitalizedWord);
  }

  return camelCaseArr.join(''); // join the array elements into a single string
}

function toCamelCase4(str) {
  let words = str.split(/[^a-zA-Z0-9]/); // split the string into an array of words
  let camelCaseArr = [words[0].toLowerCase()]; // convert the first word to lowercase and add it to the array

  // convert the first letter of each subsequent word to uppercase and add it to the array
  for (let i = 1; i < words.length; i++) {
camelCaseArr.push(words[i].charAt(0).toUpperCase());  camelCaseArr.push(words[i].slice(1).toLowerCase());
  }

  return camelCaseArr.join(''); // join the array elements into a single string
}

Teardown


Test runner

Ready to run.

Testing in
TestOps/sec
Regular expression hell (1)
toCamelCase1(str)
ready
Concat string (2)
toCamelCase2(str)
ready
Contact array (3)
toCamelCase3(str)
ready
Concat all array (4)
toCamelCase4(str)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.