Get last char of string

Benchmark created by T.J. Crowder on


Description

Check the performance of various ways to get the last character from a string. It rarely actually matters and usually different things are faster on different browsers so don't get hung up on it, but still interesting for those rare tight loops...

Preparation HTML

<script>
  var str = "This is a test of the emergency broadcasting system.";
  var a;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
substring
a = str.substring(str.length - 1);
if (a !== ".") throw "Bad result";
ready
strstr
a = str.substr(str.length - 1);
if (a !== ".") throw "Bad result";
ready
charAt
a = str.charAt(str.length - 1);
if (a !== ".") throw "Bad result";
ready
slice
a = str.slice(-1);
if (a !== ".") throw "Bad result";
ready
[]
a = str[str.length - 1];
if (a !== ".") throw "Bad result";
ready

Revisions

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

  • Revision 1: published by T.J. Crowder on