0

I need a fast way to find if a string is in a set of strings.

My set does not change much over time, so putting it in a sorted array and using binary search is an option (as advised here: fastest way to determine if an element is in a sorted array)

But would using a trie be faster considering we are talking about String ? If so, is there a well known and supported implementation I could use ? (found a few one on github, but did not seem supported or broadly used).

I was also reading: Fast way to find if a string is in an array

Any chance this approach could beat using a trie ?

(I do not have the time to try to implement all the approaches and benchmark them.)

1 Answer 1

2

You have JavaScript. If you go with trie, it would be your own implementation in JavaScript, while a hash is pretty much the foundation the whole JavaScript is built on, optimised to hell in the execution environment. I'd just do this:

var STRINGS = {
  "foo": true,
  "bar": true
}

var fooExists = STRINGS.hasOwnProperty("foo");
Sign up to request clarification or add additional context in comments.

4 Comments

maybe this is just the answer I am looking for, just that building a dictionary for such purpose is so counter intuitive ...
If it helps you with the "counter-intuitive" bit, Ruby's Set and Java's TreeSet use the exactly same method (having a composed Hash and TreeMap, respectively) ;)
yes, that actually helps :) Actually that may even explain why there are no broadly used implementation of trie ?
I don't know, really. For large databases I imagine native trie will beat a native hash (either in memory or in speed, depending on number of buckets hash is allocated with); but native hash to beat scripted trie. However, without a benchmark it's just speculation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.