I am currently working on optimizing the operations of QScriptEngine within one of my functions.
The function, called executeCustomJSOperation
, is responsible for executing the same JS code across multiple files. Each file requires a modification to a global variable called $xmlData
. Essentially, this function loads an XML file into memory using the $xmlData
variable and then applies the same JavaScript code (jsString
) to edit the XML file using JavaScript. Finally, the $xmlData
variable is updated with the edited XML content.
I managed to achieve a 2.5 speedup by implementing an OpenMP parallel for
loop over the XML files processing. However, I am now looking for ways to further enhance the speed of this function.
Below is the code snippet:
// This function allows users to echo JavaScript variables for debugging purposes through cout
QScriptValue echo(QScriptContext *context, QScriptEngine *engine)
{
std::cout << context->argument(0).toString().toUtf8().constData() << std::endl;
return "";
}
void executeCustomJSOperation(const QString &jsString, const QStringList &filesToProcess){
QString rexmlString, jsxmlString;
QFile rexmlfile(":/resources/libs/rexml.js"); // loading JavaScript libraries as strings into memory
QFile jsxmlfile(":/resources/libs/jsxml.js");
rexmlfile.open(QFile::ReadOnly | QFile::Text);
jsxmlfile.open(QFile::ReadOnly | QFile::Text);
rexmlString=QTextStream(&rexmlfile).readAll();
jsxmlString=QTextStream(&jsxmlfile).readAll();
// Processing all XmlFiles
#pragma omp parallel for // Achieved 2.5 speedup on my machine
for(int i=0; i<filesToProcess.size(); i++){
QString currXmlFileString;
QScriptEngine engine;
QScriptValue engineResult;
// Adding echo function for user debugging
QScriptValue echoFunction = engine.newFunction(echo);
engine.globalObject().setProperty("echo", echoFunction);
engine.evaluate(rexmlString); // Loading JavaScript libraries in the JS engine
engine.evaluate(jsxmlString);
QFile currXmlFile(filesToProcess[i]);
currXmlFileString=QTextStream(&currXmlFile).readAll();
currXmlFile.close();
engine.globalObject().setProperty("$xmlData",currXmlFileString);
engine.evaluate("main(); function main() {"+jsString+"}"); // The main function allows the use of 'return' statement to exit from user code
engineResult=engine.globalObject().property("$xmlData");
QTextStream(&currXmlFile) << engineResult.toString(); // Retrieving modified XML by JavaScript and saving it back to the file
}
}
Are there any suggestions on how to further optimize this code? Feel free to ask if you have any questions.