Skip to content

Instantly share code, notes, and snippets.

@gamlerhart
Last active August 31, 2017 13:51
Show Gist options
  • Save gamlerhart/d3f5a7f143dbc894b4f43c4fcbaae79f to your computer and use it in GitHub Desktop.
Save gamlerhart/d3f5a7f143dbc894b4f43c4fcbaae79f to your computer and use it in GitHub Desktop.
package info.gamlor.blog;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
enum TypeInfo {
UNKNOWN(0),
INT(1),
STRING(2);
private final int id;
TypeInfo(int id) {
this.id = id;
}
public static TypeInfo findType(int type){
for (TypeInfo t : values()){
if(t.id == type){
return t;
}
}
return UNKNOWN;
}
}
public class Main {
private static Random rnd = new Random();
public static void main(String[] args) throws Exception {
List<TypeInfo> parsedData = new ArrayList<>();
for (int i = 0; i < 1000000000; i++) {
int idParsedFromWire = readTypeIdFromData(rnd);
TypeInfo type = TypeInfo.findType(idParsedFromWire);
// Pretend we use the type for the exampe
parsedData.add(type);
consumeData(parsedData);
}
System.out.println(parsedData.size());
}
private static void consumeData(List<TypeInfo> parsedData) {
// Parsed data is consumed
if(rnd.nextBoolean()){
parsedData.clear();
}
}
private static int readTypeIdFromData(Random rnd) throws InterruptedException {
// Data comes from the wire....let's run this example a bit slower
int idParsedFromWire = rnd.nextInt(16);
Thread.yield();
return idParsedFromWire;
}
}
// Enum.values() does a defensive copy and allocates an array on each call
// To avoid that allocation, we call values() only once
private static final TypeInfo[] ALL_VALUES = values();
public static TypeInfo findType(int type){
for (TypeInfo t : ALL_VALUES){
if(t.id == type){
return t;
}
}
return UNKNOWN;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment