# two-sum-perf

## JavaScript performance comparison

Test case created by dougrich

## Preparation code

``````

<script>
Benchmark.prototype.setup = function() {
const len = 10000;
const bigArr = new Array(len)
for (let i = 0; i < len; i++) {
bigArr[i] = Math.floor(Math.random() * 9000) + 1000
}
bigArr[len - 2] = 9;
bigArr[len - 1] = 10;
const total = 19;
};

</script>
``````

## 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
brute force
``````const twoSum = (nums, total) => {
for (let i = 0; i < nums.length - 1; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === total) {
return [nums[i], nums[j]];
}
}
}
};

twoSum(bigArr, total);``````
pending…
hash
``````const twoSum = (nums, total) => {
// Keep track of previous array values
const previousValues = {};

for (let i = 0; i < nums.length; i++) {
// What previous value needs to exist for
// us to have found our solution?
const complement = total - nums[i];

if (previousValues[complement]) {
return [complement, nums[i]];
}

// This current array item now becomes
// a previous value
previousValues[nums[i]] = true;
}
};

twoSum(bigArr, total);``````
pending…
sorted
``````function twoSum (arr, num) {
arr = arr.sort()
let i = 0, j = arr.length - 1
while (true) {
let sum = arr[i] + arr[j]
if (sum === num) {
return [arr[i], arr[j]]
} else if (sum < num) {
i++
} else {
j--
}
}
}

twoSum(bigArr, total);``````
pending…

## Revisions

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