Skip to content

Instantly share code, notes, and snippets.

@RaffaeleSgarro
Created November 17, 2012 00:55
Show Gist options
  • Save RaffaeleSgarro/4092306 to your computer and use it in GitHub Desktop.
Save RaffaeleSgarro/4092306 to your computer and use it in GitHub Desktop.
Benchmark for StackOverflow
package stackoverflow;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class StringsContainingCharacters {
public static void main(String[] args) {
Strategy straight = new StraightStrategy();
Strategy trie = new TrieStrategy();
String[] sources = generateSources(100 * 1000, 14);
String input = randomString(4);
Benchmark benchmark = new Benchmark(sources, input);
System.out.println("Straight took " + benchmark.exec(straight, 10) + "ms on average");
System.out.println("Trie took " + benchmark.exec(trie, 10) + "ms on average");
}
static class StraightStrategy implements Strategy {
@Override
public void test(String[] source, String input) {
Set<Character> needle = removeDuplicates(input);
for (String src: source) {
if (contains(src, needle)) {
System.out.println(src);
}
}
}
private boolean contains(String haystack, Set<Character> chars) {
for (char c: chars) {
if (haystack.indexOf(c) < 0)
return false;
}
return true;
}
private Set<Character> removeDuplicates (String input) {
Set<Character> chars = new HashSet<Character>();
for (int i = 0; i < input.length(); i++)
chars.add(input.charAt(i));
return chars;
}
}
static class TrieStrategy implements Strategy {
@Override
public void test(String[] source, String input) {
// TODO
}
}
interface Strategy {
void test(String[] source, String input);
}
static class Benchmark {
String[] sources;
String input;
Benchmark(String[] sources, String input) {
this.sources = sources;
this.input = input;
}
// Returns the average execution time
long exec(Strategy strategy, int times) {
long start = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
strategy.test(sources, input);
}
return (System.currentTimeMillis() - start) / times;
}
}
static String[] generateSources(int howMany, int lineLength) {
String[] src = new String[howMany];
for (int i = 0; i < src.length; i++)
src[i] = randomString(lineLength);
return src;
}
static String randomString(int length) {
char[] src = new char[length];
Random generator = new Random();
for (int i = 0; i < src.length; i++)
src[i] = (char) generator.nextInt(128);
return new String(src);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment