So my app is currently reading 10k lines into a variable and then using SwiftyJson to parse it into realm.
Source: https://github.com/skishore/makemeahanzi/blob/master/graphics.txt https://github.com/skishore/makemeahanzi/blob/master/dictionary.txt
Problem: It takes way too long: 2:28minutes. Also it takes 400mb of memory!
Question: How to make this faster? Any of you having experience with Flatbuffers or Protobuf?
Help would be very welcome!
Cheers, Dom
This is the code:
func parseToRealm() {
// each of these files have 9500+ lines of data
// (basically dictionaries with word definitions)
let graphicsFileContents = readFile_Graphics()
let dictFileContents = readFile_Dict()
// check if counts of two source files match
if (graphicsFileContents.count == dictFileContents.count && graphicsFileContents.count > 1 && dictFileContents.count > 1) {
var i = 0
// make empty array of characters
var characterArr = [Characters()]
// loop through two files to get all chars
for jsonString in graphicsFileContents {
// parse data from string into json
let dataFromString = jsonString.data(using: .utf8)
let singleCharJson = try? JSON(data: dataFromString!)
// parse stuff from file1
// ... deleted lines for legal reasons
// DICT information
let dictDataFromString = dictFileContents[i].data(using: .utf8)
let singleDictJson = try? JSON(data: dictDataFromString!)
// parse stuff from that dictionary
// ... deleted lines for legal reasons
characterArr.append(Character)
// Every x characters, write them into DB
if (i % 150 == 0 || i == graphicsFileContents.count){
realmActions.writeCharsToRealm(characterArr: characterArr)
print("Writing \(i)-\(i + 150)")
// reset array to safe memory
characterArr = [Characters()]
}
i+=1
} // end loop file contents
}else{
print ("two files have different counts of lines. aborting...")
}
}
// read graphics file and return all contents as array of strings
// return Array of Strings
func readFile_Graphics () -> [String] {
// predeclare emtpy string array
var myStrings = [String]()
if let path = Bundle.main.path(forResource: "graphics", ofType: "txt") {
do {
let data = try String(contentsOfFile: path, encoding: .utf8)
myStrings = data.components(separatedBy: .newlines)
} catch {
print("cannot get file graphics.txt. Error message:")
print(error)
}
}
return myStrings
}
// read dictionary file and return all contents as array of strings
func readFile_Dict () -> [String]{
var myStrings = [""]
if let path = Bundle.main.path(forResource: "dictionary", ofType: "txt") {
do {
let data = try String(contentsOfFile: path, encoding: .utf8)
myStrings = data.components(separatedBy: .newlines)
} catch {
print("cannot get file dictionary.txt. Error message:")
print(error)
}
}
return myStrings
}