Created
March 3, 2018 04:54
-
-
Save jasongrout/af03ee55599d864649df696adfec842d to your computer and use it in GitHub Desktop.
Benchmarking loops vs regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <head> | |
| <meta charset="utf-8"/> | |
| </head> | |
| <body> | |
| <pre id="output"></div> | |
| <script> | |
| const regex = new RegExp(`[,\n\r]`, 'g'); | |
| const simpletrials = 10000000; | |
| const out = document.getElementById('output'); | |
| let simpledata = `0.0404756403057589,0.7421019027252205,0.8450241932290308,0.8827047721611573,0.58520526732853,0.4495376612871874,0.9619911101530149,0.4854921076615434,0.8964941776531551,0.31591288618194946 | |
| 0.3166362376294698,0.03284162932733392,0.51530616115736,0.674490593986978,0.1598460030189489,0.3691509763932902,0.06238009873727357,0.9651582204572289,0.41322965991461746,0.4519640670802132 | |
| 0.22819828379158458,0.3214377558025071,0.29157637419608706,0.905317592296178,0.5590750639010186,0.729186364105792,0.31352940446213684,0.0026487009233953085,0.6069714812974216,0.2911053931929254 | |
| `; | |
| let c; | |
| function loop_test(data, start, trials) { | |
| const CH_DELIMITER = ','.charCodeAt(0); | |
| const CH_LF = 10; // \n | |
| const CH_CR = 13; // \r | |
| let loop_char; | |
| let loop_i; | |
| for (let c = 0; c<trials; c++) { | |
| loop_i = start; | |
| while (loop_i < 1000-2) { | |
| loop_char = data.charCodeAt(loop_i); | |
| if (loop_char === CH_DELIMITER || loop_char === CH_LF || loop_char === CH_CR) { | |
| break; | |
| } | |
| loop_i++; | |
| } | |
| } | |
| return loop_i | |
| } | |
| function regex_test(data, start, trials, regex) { | |
| let regex_char; | |
| let regex_i; | |
| let match; | |
| for (let c = 0; c<trials; c++) { | |
| regex.lastIndex = start; | |
| match = regex.exec(simpledata); | |
| if (match) { | |
| regex_i = match.index; | |
| regex_char = simpledata.charCodeAt(regex_i); | |
| } | |
| } | |
| return regex_i; | |
| } | |
| let rStart = performance.now(); | |
| let regex_out = regex_test(simpledata, 19, simpletrials, regex); | |
| let rEnd = performance.now(); | |
| let rTime = (rEnd - rStart)/1000; | |
| out.textContent = `regex: ${rTime}`; | |
| let lStart = performance.now(); | |
| let loop_out = loop_test(simpledata, 19, simpletrials); | |
| let lEnd = performance.now(); | |
| let lTime = (lEnd - lStart)/1000; | |
| out.textContent = out.textContent + `\nloops: ${lTime}`; | |
| if (loop_out === regex_out) { | |
| out.textContent = out.textContent + `\nResults: i=${loop_out}` | |
| } else { | |
| out.textContent = out.textContent + `\nResults: did not match` | |
| } | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment