Drupal.checkPlain (v2)

Revision 2 of this benchmark created by technosophos on


Description

This is a performance test between two variations on make a string plain text.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  var testData = '<This> is a test & string ".';
  var checkPlain1 = function(str) {
   var character, regex, replace = {
    '&': '&amp;',
    '"': '&quot;',
    '<': '&lt;',
    '>': '&gt;'
   };
   str = String(str);
   for (character in replace) {
    if (replace.hasOwnProperty(character)) {
     regex = new RegExp(character, 'g');
     str = str.replace(regex, replace[character]);
    }
   }
   return str;
  };
  
  var checkPlain2 = function(str) {
   var length, r = new RegExp('(&)|(\")|(<)|(>)|([^&\"<>]*)', 'g'),
       replacements = ["&amp;", "&quot;", "&lt;", "&gt;"],
       retval = '',
       match = r.exec(str);
   while (match[0] != "") {
    length = match.length;
    for (var i = 1; i < length; ++i) {
     if (match[i] != undefined) {
      retval += (i == 5 ? match[i] : replacements[i - 1]);
     }
    }
    match = r.exec(str);
   }
  
   return retval;
  };
  
  var checkPlain3 = function(str) {
   var r = new RegExp('(&)|(\")|(<)|(>)|([^&\"<>]*)', 'g'),
       replacements = ["&amp;", "&quot;", "&lt;", "&gt;"],
       retval = '',
       match = r.exec(str);
   while (match[0] != "") {
    for (var i = 1; i < match.length; ++i) {
     if (match[i] != undefined) {
      retval += (i == 5 ? match[i] : replacements[i - 1]);
     }
    }
    match = r.exec(str);
   }
  
   return retval;
  };
  
  function checkPlain4(str) {
   var replace = {
    '&': '&amp;',
    '"': '&quot;',
    '<': '&lt;',
    '>': '&gt;'
   },
       chars = str.split(''),
       len = chars.length,
       out = '';
   for (var i = 0; i < len; ++i) {
    if (replace[chars[i]] != undefined) {
     out += replace[chars[i]];
    }
    else {
     out += chars[i];
    }
   }
   return out;
  };
  
  function checkPlain5(str) {
   var replace = {
    '&': '&amp;',
    '"': '&quot;',
    '<': '&lt;',
    '>': '&gt;'
   },
       len = str.length,
       out = '';
   for (var i = 0; i < len; ++i) {
    if (replace[str[i]] != undefined) {
     out += replace[str[i]];
    }
    else {
     out += str[i];
    }
   }
   return out;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Multi Pass
checkPlain1(testData);
ready
Single Pass
checkPlain2(testData);
ready
Single Pass Take 2
checkPlain3(testData);
ready
No regexp
checkPlain4(testData);
ready
No reg or split
checkPlain5(testData);
ready

Revisions

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

  • Revision 1: published by Matt Farina on
  • Revision 2: published by technosophos on
  • Revision 3: published by technosophos on