In Sample? (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script src="
https://cdn.jsdelivr.net/npm/xxhashjs@0.2.2/build/xxhash.min.js
"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/murmurhash3js/3.0.1/murmurhash3js.min.js"></script>

Setup

const generateHashCode = function (str) {
  let hash = 0;
  if (str.length === 0) return hash;
  for (let i = 0; i < str.length; i++) {
    const chr = str.charCodeAt(i);
    hash = (hash << 5) - hash + chr;
    hash |= 0;
  }
  return hash;
};

const isSessionInSample = function (sessionId, sampleRate) {
  const hashNumber = generateHashCode(sessionId.toString());
  const absHash = Math.abs(hashNumber);
  const absHashMultiply = absHash * 31;
  const mod = absHashMultiply % 100;
  return mod / 100 < sampleRate;
};

const isSessionInSampleHigherGranularity = function (sessionId, sampleRate) {
  const hashNumber = generateHashCode(sessionId.toString());
  const absHash = Math.abs(hashNumber);
  const absHashMultiply = absHash * 31;
  const mod = absHashMultiply % 1000000;
  return mod / 1000000 < sampleRate;
};

const isSessionInSampleXXHash = function (sessionId, sampleRate) {
  const mod = XXH.h32( sessionId.toString(), 0xABCD ).toNumber() % 100;
  return mod / 100 < sampleRate;
};

const isSessionInSampleMurmur = function (sessionId, sampleRate) {
  const mod = murmurHash3.x86.hash32(sessionId.toString()) % 100;
  return mod / 100 < sampleRate;
};

Test runner

Ready to run.

Testing in
TestOps/sec
Before
isSessionInSample(String(Date.now()))
ready
Higher Granularity
isSessionInSampleHigherGranularity(String(Date.now()))
ready

Revisions

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