Compare string to array convertio
Compares function with and without using regexp.
by Maciej Sikora
HTML
<script src="https://cdn.rawgit.com/StartCodingPL/startjs/master/startjs.js"></script>
<script src="https://cdn.rawgit.com/maciejsikora/Speeder/master/speeder.js"></script>
JavaScript
//solution without regexp
function convertStringToArray(str, maxPartSize){
const chunkArr = [];
let leftStr = str;
do {
chunkArr.push(leftStr.substring(0, maxPartSize));
leftStr = leftStr.substring(maxPartSize, leftStr.length);
} while (leftStr.length > 0);
return chunkArr;
};
//solution with regexp
function convertStringToArrayRegex(str, maxPartSize){
const reg = new RegExp(".{1,"+maxPartSize+"}", "g");
return str.match(reg);
};
//create example string
function createString(size){
const symbols=["a","b","c","d","e","f","1","2","3","4"];
let str="";
for ( let i = 0; i<size; i++){
str+=symbols[Math.floor((Math.random() * 10))];
};
return str;
}
//TEST PERFORMANCE
const sp=new Speeder();
info("TEST ON 30 CHAR STRING");
str=createString(30);
sp.start("noregex");
convertStringToArray(str, 5);
sp.end("noregex");
write(sp.result("noregex"));
sp.start("regex");
convertStringToArrayRegex(str, 5);
sp.end("regex");
write(sp.result("regex"));
info("TEST ON 1000 CHAR STRING");
str=createString(1000);
sp.start("noregex");
convertStringToArray(str, 5);
sp.end("noregex");
write(sp.result("noregex"));
sp.start("regex");
convertStringToArrayRegex(str, 5);
sp.end("regex");
write(sp.result("regex"));
info("TEST ON 10000 CHAR STRING");
str=createString(10000);
sp.start("noregex");
convertStringToArray(str, 5);
sp.end("noregex");
write(sp.result("noregex"));
sp.start("regex");
convertStringToArrayRegex(str, 5);
sp.end("regex");
write(sp.result("regex"));
info("TEST ON 1 000 000 CHAR STRING");
str=createString(1000000);
sp.start("noregex");
convertStringToArray(str, 5);
sp.end("noregex");
write(sp.result("noregex"));
sp.start("regex");
convertStringToArrayRegex(str, 5);
sp.end("regex");
write(sp.result("regex"));
info("TEST ON 1 000 000 CHAR STRING WITH BIG CHUNKS");
str=createString(1000000);
sp.start("noregex");
convertStringToArray(str,...