javascriptperformancestripcode-complexity

Which way is faster when stripping part of string in JavaScript


I need to strip part of JWT token and I am courious which one is faster, or less complex internally.

Example input string:

const input = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjMsInR5cGUiOjAsImlhdCI6MTU4MTk3NDk1MCwiZXhwIjoxNTgxOTc4NTUwfQ.oEwxI51kVjB6jJUY2N5Ct6-hO0GUCUonolPbryUo-lI"

Which one of those methods is faster?

const output =  input.split('.').slice(2,3).join('.');
const output =  input.replace("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.","");
const output =  //REGEX replace

I not found any informations about speeds of those methods and I am not exactly master in making tests :D


Solution

  • For things like this, measuring execution time never makes sense, however, using string functions will most likely outperform both of your examples

    const input = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjMsInR5cGUiOjAsImlhdCI6MTU4MTk3NDk1MCwiZXhwIjoxNTgxOTc4NTUwfQ.oEwxI51kVjB6jJUY2N5Ct6-hO0GUCUonolPbryUo-lI";
    
    console.log(input.substr(input.indexOf('.') + 1));