chakra-core / chakra-core/ChakraCore

Performance: Modulus operator is slow

Open
#5,432 0 comments 4 reactions 0 assignees View on GitHub
Performance
Dominant language
JavaScript
Stars
9.3k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

I recently wrote a prime number generator which I noticed ran significantly slower on Chakra than on other engines:

```js
"use strict";

const numberOfPrimes = 1000000;

const primes = new Uint32Array(10000001);
const products = new Uint32Array(10000001);
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
products[0] = 4;
products[1] = 9;
products[2] = 25;
products[3] = 49;

let possible = 7;
let length = 4;

function nextPrime()
{
let looking = true;

while (looking)
{
possible += 2;
looking = !checkNumber();
}
primes[length] = possible;
products[length] = possible * possible;
++length;
}

function checkNumber()
{
let result = true;

for (let i = 1; products[i] <= possible; ++i)
{
if ((possible % primes[i]) === 0)
{
result = false;
break;
}
}
return result;
}

const start = Date.now();

while (length < numberOfPrimes)
{
nextPrime();
}
const end = Date.now();

print(`Generated ${numberOfPrimes - 4} primes and took = ${end - start} milliseconds`);
print(`The last prime was ${primes[numberOfPrimes - 1]}`);
```

Testing on my MacBook pro in Jsc that takes around 2 seconds to run, in v8 around 2.1 seconds and in ch around 3.8 seconds.

Replacing the use of the modulus operation '%' with the following function equalised jsc and ch at 2.1 seconds:
```js
function fastMod(numerator, denominator)
{
return numerator - (numerator / denominator|0) * denominator;
}
```

Examining JavaScriptCore's source as compared with ChakraCore's source the relevant difference is that JavaScriptCore has a method to generate a fast inline modulus operator whereas ChakraCore always uses a helper call.

Not sure how significant this would be in most real world code - the modulus operator probably isn't on lots of hot paths but considering that jsc, v8 and SM already optimise this the lack of optimisation in CC may come as a surprise to developers.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.