Advertisement
k98kurz

ucwords js speed comparison

May 16th, 2023
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function ucfirst (str) {
  2.     let s = str[0].toUpperCase() + str.substr(1);
  3.     return s;
  4. }
  5.  
  6. function ucwords1 (str) {
  7.     let parts = str.split(' ');
  8.     for (let i=0, l=parts.length; i<l; ++i) {
  9.         parts[i] = ucfirst(parts[i]);
  10.     }
  11.     return parts.join(' ');
  12. }
  13.  
  14. function ucwords2 (str) {
  15.     return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
  16.         return $1.toUpperCase();
  17.     });
  18. }
  19.  
  20. function benchmark(fn, times=1000) {
  21.     let ts1 = Date.now();
  22.     for (let i=0; i<times; ++i)
  23.         fn();
  24.     let ts2 = Date.now();
  25.     return ts2 - ts1;
  26. }
  27.  
  28. console.log(benchmark(() => ucwords1('lorem ipsum dolor sit amet, something something i am the law'), 1e6));
  29. // three trials: 958ms, 1035ms, 975ms; avg=989.333...ms
  30. console.log(benchmark(() => ucwords2('lorem ipsum dolor sit amet, something something i am the law'), 1e6));
  31. // three trials: 2177ms, 2237ms, 2426ms; avg=2280ms
  32. // 989.333/2280 = 0.434; ucwords1 is ~60% faster than ucwords2
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement