Loading ...
Sorry, an error occurred while loading the content.

1464slice method appears slower in loops than incrementally listing array indexes

Expand Messages
  • Cheney, Edward A SSG RES USAR
    Sep 3, 2010
    • 0 Attachment
      Group,

      I am trying to figure out why slice appears to be slower when executed upon a large string than merely pointing to a group of indexes. My presumption is that slice should be faster, but in my tests it is definitely slower. Here are some code examples:

      var a, i, x = "some large string of greater than 150kb", y = x.split(''), z = y.length;
      for (i = 0, i < z; i += 1) {
      if (y[i] + y[i + 1].toLowerCase() + y[i + 2].toLowerCase() + y[i + 3].toLowerCase() + y[i + 4].toLowerCase() + y[i + 5].toLowerCase() + y[i + 6].toLowerCase() === "<style") {
      a = "some value";
      }
      }
      for (i = 0, i < z; i += 1) {
      if (x.slice(i, i + 7) === "<style") {
      a = "some value";
      }
      }

      The second loop is much easier to read and I presume it would be faster because it is searching an index of a string, but it is only performing that search once per iteration of the loop. The first loop is ugly to look at, but appears faster in Firefox and Opera, which is surprising because it is performing 7 different look ups into an array per loop iteration. It is further surprising considering that large data segments would presumed to be more memory efficient as a joined string opposed to associating each character with an array index. The larger the tested string the more disparaging the results become.

      My question is why is the second loop, the pretty one, slower than the first loop? Even more strange I have found an exception to this test where the second loop becomes faster than the first loop only if the value of Z is subject to change per loop iteration, but the difference of speed in this exception is less than the difference of speed evident in the stated examples.

      Thanks,

      Austin
      http://prettydiff.com/
    • Show all 5 messages in this topic