k98kurz icon

ucwords js speed comparison

k98kurz | PRO | 05/16/23 04:19:29 PM UTC | 0 ⭐ | 912 👁️ | Never ⏰ | []
JavaScript |

970 B

|

None

|

0 👍

/

0 👎

function ucfirst (str) {
    let s = str[0].toUpperCase() + str.substr(1);
    return s;
}
 
function ucwords1 (str) {
    let parts = str.split(' ');
    for (let i=0, l=parts.length; i<l; ++i) {
        parts[i] = ucfirst(parts[i]);
    }
    return parts.join(' ');
}
 
function ucwords2 (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}
 
function benchmark(fn, times=1000) {
    let ts1 = Date.now();
    for (let i=0; i<times; ++i)
        fn();
    let ts2 = Date.now();
    return ts2 - ts1;
}
 
console.log(benchmark(() => ucwords1('lorem ipsum dolor sit amet, something something i am the law'), 1e6));
// three trials: 958ms, 1035ms, 975ms; avg=989.333...ms
console.log(benchmark(() => ucwords2('lorem ipsum dolor sit amet, something something i am the law'), 1e6));
// three trials: 2177ms, 2237ms, 2426ms; avg=2280ms
// 989.333/2280 = 0.434; ucwords1 is ~60% faster than ucwords2
 

Comments