Skip to content

Instantly share code, notes, and snippets.

@spullara spullara/Render.java
Last active Jan 14, 2017

Embed
What would you like to do?
Comparing performance between Java and Swift
string render(string text, set<Entity> *entitySet) {
string result = "";
auto entityList = list<Entity>(entitySet->begin(), entitySet->end());
entityList.sort();
int pos = 0;
for (list<Entity>::const_iterator entity = entityList.begin(), end = entityList.end(); entity != end; ++entity) {
result.append(text.substr(pos, entity->start - pos));
result.append(entity->html);
pos = entity->end;
}
result.append(text.substr(pos));
return result;
}
public CharSequence render(String text, Set<Entity> entities) {
StringBuilder sb = new StringBuilder(256);
Entity[] array = entities.toArray(new Entity[entities.size()]);
Arrays.sort(array);
int pos = 0;
int codePointPosition = 0;
for (Entity entity : array) {
int start = text.offsetByCodePoints(pos, entity.start - codePointPosition);
sb.append(text, pos, start);
sb.append(entity.html);
codePointPosition = entity.end;
pos = text.offsetByCodePoints(start, entity.end - entity.start);
}
sb.append(text, pos, text.length());
return sb;
}
func render(text: String, entities: Set<Entity>) -> String {
let entityArray: Array<Entity> = Array(entities).sorted(by: {(e1: Entity, e2: Entity) -> Bool in return e1.start - e2.start < 0})
var sb = String()
var pos = 0
var posIndex = text.startIndex
for entity in entityArray {
let startIndex = text.index(posIndex, offsetBy: entity.start - pos)
let endIndex = text.index(startIndex, offsetBy: entity.end - entity.start)
sb.append(text.substring(with: posIndex ..< startIndex))
sb.append(entity.html)
posIndex = endIndex
pos = entity.end
}
sb.append(text.substring(from: posIndex))
return sb
}
func render2(text: String, entities: Set<Entity>) -> String {
var sb: Array<Character> = Array()
sb.reserveCapacity(256)
let chars = ArraySlice(text.characters)
let entityArray: Array<Entity> = Array(entities).sorted(by: {(e1: Entity, e2: Entity) -> Bool in return e1.start - e2.start < 0})
var pos = 0
for entity in entityArray {
sb.append(contentsOf: chars[pos..<entity.start])
sb.append(contentsOf: entity.html.characters)
pos = entity.end
}
sb.append(contentsOf: chars.suffix(from: pos))
return String(sb)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.