Single vs Multiple regex

Benchmark created on


Setup

const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;
const DYNAMIC_INPUT_TAG = new RegExp(`%%(([\\w-]+)\\.(${UUID.source})\\.(\\w+))%%`); const DYNAMIC_INPUT_TAG_GLOBAL = new RegExp(DYNAMIC_INPUT_TAG.source, 'g');

const testString = "It also contains a 'b', look!%%llm-summarize-text.3ac48323-3c7a-4ab2-86b0-47f5a32f07a4.SummarizedText%%. Received it at %%gmail-get-all-new-messages.5ffbfc78-7c7e-4065-8354-03b6d8456805.receivedAt%%%%slack-send-channel-message.282a56df-f524-43f4-aa48-6fdd58dc70ee.message_text%%" * 10000;


const splitDynamicInputValueV1 = (value) => {
  let cursor = 0;
  const parts = [];
  while (cursor < value.length) {
    const str = value.slice(cursor);
    const match = str.match(DYNAMIC_INPUT_TAG);
    if (!match) {
      parts.push(str);
      break;
    }

    const [tag, _, operation, nodeId, code] = match;
    parts.push(str.slice(0, match.index));
    parts.push({ operation, nodeId, code });
    cursor += match.index + tag.length;
  }

  return parts;
};


const splitDynamicInputValueV2 = (value) => {
  const parts = [];
  let lastIndex = 0;
  let match;

  // Reset regex state for global regex
  DYNAMIC_INPUT_TAG_GLOBAL.lastIndex = 0;
  
  while ((match = DYNAMIC_INPUT_TAG_GLOBAL.exec(value)) !== null) {
    const [fullMatch, tagId, operation, nodeId, code] = match;
    
    // Add text before the match (if any)
    if (match.index > lastIndex) {
      parts.push(value.slice(lastIndex, match.index));
    }
    
    // Add the dynamic tag
    if (operation && nodeId && code) {
      parts.push({ operation, nodeId, code });
    }
    
    lastIndex = match.index + fullMatch.length;
  }
  
  // Add remaining text after last match
  if (lastIndex < value.length) {
    parts.push(value.slice(lastIndex));
  }
  
  return parts;
};

Test runner

Ready to run.

Testing in
TestOps/sec
Slice the string
splitDynamicInputValueV1(testString);
ready
Global regex
splitDynamicInputValueV2(testString);
ready

Revisions

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