Timeline for Simple n-body class in C++
Current License: CC BY-SA 4.0
8 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Oct 24, 2019 at 10:42 | comment | added | eanmos |
@Samuel, in short. i++ must create a copy of the old value, "return" it and then increment i . In the same time ++i doesn't have to create a copy and "return" it, it increments i and just "return" it. For build-in types (such as int ) the compiler probably be able to optimize your code. But i can be an instance of a C++ class so i++ and ++i making calls to one of the operator++ function. In that case the compiler probably not be able to optimize and then copying of an object i when using i++ can be really slow. So in general case just use ++i .
|
|
Oct 24, 2019 at 10:31 | comment | added | Gilfoyle |
@eanmos Should I always use ++i instead of i++ in for-loops? Why is it faster?
|
|
Oct 24, 2019 at 7:12 | comment | added | ashiswin |
@eanmos fair enough. It was more of the assertion that "In C++ the ++ comes before the variable, in other languages like Java or C or Go it comes after the variable." But yes, the convention would be to use ++i .
|
|
Oct 24, 2019 at 7:11 | comment | added | eanmos |
yes, but it is a good habit to write ++i by default and use post increment only when it is need to be used.
|
|
Oct 24, 2019 at 7:03 | comment | added | ashiswin |
@eanmos, that is possible, but in the link you provided it states that this performance hit is usually only present if the type being incremented is not a primitive type. However in OP's post, step is of type int , which should be optimized correctly by the compiler.
|
|
Oct 24, 2019 at 6:52 | comment | added | eanmos |
I think that Rolan Illig meant that ++i usually is faster than i++ .
|
|
Oct 24, 2019 at 6:50 | review | First posts | |||
Oct 24, 2019 at 7:12 | |||||
Oct 24, 2019 at 6:46 | history | answered | ashiswin | CC BY-SA 4.0 |