string hashing perf

Benchmark created on


Setup

const stringz = [
'Y3hXaLp9Rt7JkDZ82oFvM',
'BvWkL7Xp1oF28DY9RMJh6Ztnc',
'5YTqG8Fn1pL7vMXRt92oKZcDh',
'Zv5Lp8R7Wk9MXtn1DY2Jq6oF',
'1KXq7Lp9RM5Yn8Z2JoFWvD6tc',
'L9Z8XpD7Rt5Y2JqMXvno6KF1W',
'1RMZ6XpDY9L7Fn5Jo8tWqv2oK',
'8Lp9XtW7KMZR1FYnD6Jq5vo2c',
'YX9ZRMp7n6JoLvWqFt812K5oDc',
'YpM9LXtRW7K8nZJq5F2o6D1vo',
'5WoKZRM8t9LY1Jq7nD2XvFp6c',
'L2RMp9X7o8WJv6FK5nYq1DtcZ',
'8WvLpX7oRM5ZFnY2Jq916DKtc',
'YZ8Lp7XRM9Jo5FKWn6q12Dtcv',
'9MRpLY5WZ2Jq8oX7n6DK1tvcF',
'ZpW8LYXqRMv5tDK7n9Jo2F1o6c',
'7F8p9LYJo1WMXqKZRn26tv5oDc',
'Z9p8YoX1tKMJq5LYR7F26nvoDc',
'YLYJq9nZRMpKt5oDXv16W87Fo2',
'9Xp7ZtY1F26RMqLvDKJ5on8oWc',
];

const testHashFn = (fn) => {
	try {
  stringz.forEach(fn);
  } catch (e) {
  	console.log('DERP ERROR', e)
  }
};

Test runner

Ready to run.

Testing in
TestOps/sec
chatgpt
function hashString(str) {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = (hash << 5) - hash + str.charCodeAt(i);
    // Force hash into 32-bit integer
    hash |= 0; 
  }
  return hash;
}

testHashFn(hashString);
ready
gist - 4nte
function hashCode(s) {
    let h;
    for(let i = 0; i < s.length; i++) 
          h = Math.imul(31, h) + s.charCodeAt(i) | 0;

    return h;
}

testHashFn(hashCode);
ready
gist - jschirrmacher
function hashCode(str) {
  return Array.from(str)
    .reduce((s, c) => Math.imul(31, s) + c.charCodeAt(0) | 0, 0)
}

testHashFn(hashCode);
ready
gist - eru123
const hashCode = (str) => [...str].reduce((s, c) => Math.imul(31, s) + c.charCodeAt(0) | 0, 0);

testHashFn(hashCode);
ready

Revisions

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