body-parser
body-parser copied to clipboard
improve performance of strict
In our project we send long string to our server (2mb). Playing with settings I noticed that, if we set strict false parsing is 5-10 ms faster. Digging dipper I've found that firstCharacter is slow. Looking at regexp it seems like it can be simplified. We are looking for first character which is not \x20\x09\x0a\x0d https://regex101.com/r/X2eWbf/1 Search will be stopped after first match because regexp doesn't use global modifier
How I tested it
function makeRandomString(length) {
var result = '';
var characters = ' {ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
var str = makeRandomString(2000000);
var OLD_FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/
var NEW_FIRST_CHAR_REGEXP = /[^\x20\x09\x0a\x0d]/
console.time()
console.log(OLD_FIRST_CHAR_REGEXP.exec(str)[0])
console.timeEnd();
console.time();
console.log(NEW_FIRST_CHAR_REGEXP.exec(str)[0])
console.timeEnd();
Time difference 100-1000 times for 2mb string.
If we want to achieve really good performance here we should iterate using javascript. Because probability that first non whitespace character is placed on a first position high it would be fast.