flx
flx

Reputation: 1578

JS - replacing multiple occurrences

I'm currently writing a simple converter in javascript where I have to replace a couple of strings.

I know that you can replace those by using:

  1. regex: "string".replace(/s/g, "");
  2. split-join: "string".split("s").join("")

Which of those variants is better? (persistence, time etc.)

I prefer the second one because of its readability.

Upvotes: 1

Views: 188

Answers (3)

Erdogan Kurtur
Erdogan Kurtur

Reputation: 3685

"Better" is relative. You have to define it.

Memory-wise less allocations is always better. Computation-wise, hard-coded solutions generally provide better results. All operations takes some time, but in JS it depends on the virtual machine that script runs.

If provided code will be called 1000 times a day per user, then it really does not matter. You cannot achieve "better" performance.

If you are after "better" splitting, than regex is your buddy. In this case "better" means "unicode support", "non-latin character support", "less code" and of course some difficult to code operation like splitting by uppercase letters only if they are after a lowercase letter.

RegEx is a language, in my humble opinion, every programmer must learn. Basic syntax is enough for most operations.

Imagine how many lines you would have to write to find a letter in a string repeated three or more times consecutively. RegEx is \w\1\1 and you are done.

Upvotes: 1

Toto
Toto

Reputation: 91375

Here is a benchmark (in perl, but it will be similar in javascript):

#!/usr/bin/perl
use Benchmark qw(:all);

my $str = "string";

my $count = -3;
cmpthese($count, {
    'split.join' => sub {
        $str = join'',split's',$str;
    },
    'regex' => sub {
        $str =~ s/s//g;
    },
});

Output:

                 Rate split.join      regex
split.join  5068934/s         --       -76%
regex      20811069/s       311%         --

As you can see, regex is about 4 times quicker than consecutive 2 functions split and join.

Upvotes: 1

ehmprah
ehmprah

Reputation: 154

Regexes are almost always faster; in this case especially: you are building an array from a string, which can be costly depending on the size of the string. You can easily test this youself with a few different strings and few thousand runs. I'd clearly recommend the regex though.

Upvotes: 1

Related Questions