Implicit/Explicit type conversion

JavaScript performance comparison

Test case created by Kyle Simpson

Info

Want to test the effects of using variable values that must be implicitly type-coerced versus explicitly coercing them.

Preparation code

<script>
  var num_1 = 10;
  var num_2 = "10";
  var result_1, result_2, i;
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
implicit coercion required
result_1 = "";
result_2 = 0;

for (i = 0; i < 10000; i++) {
 result_1 += num_1; // 10 will be auto-coerced to "10"
 result_2 += (num_2 - 0); // "10" will be auto-coerced to 10
}
pending…
no coercion required
result_1 = 0;
result_2 = "";

for (i = 0; i < 10000; i++) {
 result_1 += num_1; // no coercion required
 result_2 += num_2; // no coercion required
}
pending…
explicit coercion
result_1 = "";
result_2 = 0;

for (i = 0; i < 10000; i++) {
 result_1 += String(num_1); // 10 explicitly coerced to "10"
 result_2 += +num_2; // "10" explicitly coerced to 10
}
pending…
explicit coercion #2
result_1 = "";
result_2 = 0;

for (i = 0; i < 10000; i++) {
 result_1 += String(num_1); // 10 explicitly coerced to "10"
 result_2 += ~~num_2; // "10" explicitly coerced to 10
}
pending…

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

Compare results of other browsers

0 comments

Add a comment