0

In JavaScript is the former or the latter more efficient? Or is there even a difference?

// Method one
var path = first_part + '/' + second_part + '/' + third_part;

// Method two
var path = [first_part, second_part, third_part].join('/');

Beyond the savings of a whopping two characters there's no visual reason to prefer one over the other. But I'm curious to know if in most JavaScript interpreters one is faster or more efficient than the other and if so, is it significantly so?

Darrell Brogdon
  • 6,843
  • 9
  • 47
  • 62
  • 2
    [What is the best way to profile javascript execution?](http://stackoverflow.com/questions/855126/what-is-the-best-way-to-profile-javascript-execution) – Robert Harvey Oct 15 '12 at 23:11
  • 4
    micro optimization at best.... seriously in this case go for what is more readable to you. for me it is the first. – rlemon Oct 15 '12 at 23:16
  • This question has been asked and re-asked ad-nauseam. Short answer: It depends not only on the javascript engine version (browser) but also on the number of strings and lengths of those strings. – Jeremy J Starcher Oct 15 '12 at 23:31
  • It seldom pays to waste effort optimizing client-side code like JavaScript, especially at such a low level. It makes more sense to just use whichever approach seems more readable to you. – aroth Oct 15 '12 at 23:45
  • Agree with you all that it is minor. And I did suspect it had been asked a thousand times but how do you search for something like that? :) Ultimately I'm just curious. I know PHP suffers--or at least used to suffer--from severe inefficiencies in string concatenation so I wondered if the same existed in most JS interpreters. – Darrell Brogdon Oct 16 '12 at 15:27

2 Answers2

2

The second method is more efficient in terms of maintenance if you ever need to change the delimiter.

Nick
  • 6,366
  • 5
  • 43
  • 62
1

Using the concatenation operator is faster than using join():

See:

See also:

Community
  • 1
  • 1
coderabbi
  • 2,261
  • 16
  • 18