# Finding Maximum Element in an Array

## JavaScript performance comparison

Test case created by Mario Klingemann

## Preparation code

``````<div id="t1"></div>
<div id="t2"></div>
<div id="t3"></div>
<div id="t4"></div>
<div id="t5"></div>
<script>
var data = [];
for (var i = 0; i < 2000; data[i++] = Math.random() * 100) {}
</script>

<script>
Benchmark.prototype.setup = function() {
var result;

};

Benchmark.prototype.teardown = function() {
document.getElementById(result.id).innerHTML = result.m;
};

</script>
``````

## Preparation code output

<div id="t1"></div> <div id="t2"></div> <div id="t3"></div> <div id="t4"></div> <div id="t5"></div>

## Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Loop
``````var d = data;
var m = d[d.length - 1];
for (var i = d.length - 1; --i > -1;) {
if (d[i] > m) m = d[i];
}
result = {id:"t1",m:m};``````
pending…
Math.max.apply()
``````var m = Math.max.apply(null, data);
result = {id:"t2",m:m};``````
pending…
sort (destructive)
``````var m = data.sort(function(a, b) {
return b - a;
})[0];
result = {id:"t3",m:m};``````
pending…
sort (non-destructive)
``````var m = data.concat().sort(function(a, b) {
return b - a;
})[0];
result = {id:"t4",m:m};``````
pending…
Max.bind
``````var aMax = Math.max.apply.bind(Math.max, Math);
var m = aMax(data);
result = {id:"t5",m:m};``````
pending…

## Revisions

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