fastify / fastify

Fast and low overhead web framework, for Node.js

Home Page:https://www.fastify.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Implement simple B-Tree for faster string comparisons

Uzlopak opened this issue · comments

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Implement a B-Tree Class

Motivation

Lets see following lines

if (method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'TRACE' || method === 'SEARCH' ||

This is run on every request. It means, that the last condition, here method === 'LOCK' is the slowest, as we have to check first 7 other values, before we potentially hit LOCK.

We should implement some simple and understandable b-tree, which only returns true if the element is in the tree and false if not.

Maybe there are other places we can use it.

Maybe using a Map is sufficient? But I think a b-tree would be faster.

Example

const MethodWithBody = new Tree()

MethodWithBody.insert('POST')
MethodWithBody.insert('PATCH')
MethodWithBody.insert('PUT')
MethodWithBody.insert('PROPFIND')

if (MethodWithBody.has(method)) {
}

Can you see this? We recently landed it and Set performed a little better, it might already be using something like that under-the-hood:

#5419

I dont think that Set is optimized for this case, as Set also handles Objects and numbers etc.. So Set must have some code to check if the type is the same and stuff like that. I have the feeling that a b-tree will be significantly faster.

A switch statement could be more efficient as it allows for direct comparison and may be optimized by the JavaScript engine.

I kind of doubt that switch case is faster.

Linear search is very often more efficient than Binary search when the number of items is tiny. I would be very surprised if implementing a binary search for this use case would be faster (regardless Big-O notation).