1

I am learning Javascript from CrockFord video "Crockford on javascript" and I am watching : "Function The Ultimate" In one of his code "he was talking about " pseudo parameters" " I saw something like this :

for( i = 0; i<n; i+=1)

So why he is not using the increment operator "++" and he is using the "+=", i know they do the same but is there a performance difference ?
Thank you.

DeltaWeb
  • 11
  • 3
  • Info here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators – elclanrs Jun 04 '14 at 22:15
  • 2
    `++` is plus 1 and `+=` can be plus X. In your instance they both do the same thing since you are adding by only 1. edit: should have read the end part of the question..I can't speak on performance difference, but I would imagine not much – Ronnie Jun 04 '14 at 22:16
  • `i = i + 1` == `i += 1` == `i ++` == `++ i` (although what each of those returns when used inside a larger expression is another matter) – Dave Jun 04 '14 at 22:19
  • Mr. Crockford doesn't like `++` for some reason: see http://stackoverflow.com/questions/971312/why-avoid-increment-and-decrement-operators-in-javascript – georg Jun 04 '14 at 22:23

2 Answers2

3

As the OP is talking about performance, I set up a JSPerf to see how the two compare. Go ahead and test this out for yourself:

http://jsperf.com/inc-vs-plus-one

Evan Kennedy
  • 3,975
  • 1
  • 25
  • 31
  • Nice. +1 and kudos. I think the performance will vary with the browser, in particular, the javascript engine. I estimate that any "real world" difference will be immeasurable. – spencer7593 Jun 04 '14 at 22:21
  • 1
    This sounds to me like a Chrome bug more than anything else. – Chuck Jun 04 '14 at 22:22
  • I think you may be right. I'll remove my comment at the end of the answer so that it doesn't lead anyone to believe that one out-performs another. – Evan Kennedy Jun 04 '14 at 22:22
  • Ok , so i see that there is a very very insignifiant performance difference , but which one do you recommend to use? – DeltaWeb Jun 04 '14 at 22:40
  • It's honestly 100% personal preference. I'll usually use `++` but that's because I personally read code easier when using that. However, I also sometimes have cleaner one-line code when using `++` within another line of code. It can save the use of a bracket in this case, but that's about the only difference it will make. – Evan Kennedy Jun 04 '14 at 22:47
1

There's no measurable performance difference. You'd be hard pressed to write a test case in which you could measure any difference.

As Ronnie pointed out in his comment, the ++ operator increments by 1, but the += can add an amount other than 1.

spencer7593
  • 106,611
  • 15
  • 112
  • 140
  • I should strike my comment about writing a test case that demonstrates a performance difference. +1 and kudos to Evan Kennedy for such a test case. – spencer7593 Jun 04 '14 at 22:24