Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
@shaikadil writing an array to memory is relatively heavy compared to a if statement as far as I know, but it probably depends on the language as well
-
aritzh7527y@Codex404 that array is compile time constant, so it will probably be compiled into the executable, which means it will probably be just as fast as the other options (at least on compiled languages).
The other two options, however, might need some kind of branching, because the compiler might not know how to optimize the if, whereas the las one should be an and (mod 2), load and call. So it will probably be like one or two cpu cycles faster. -
okkimus17187y@aritzh
Still the CPU needs to access the array, which might be more costly operation.
The compilation point is valid and the execution time might vary by how the code is optimized. In this code example the difference is nevertheless non-existent :D unless you need to do the operation 100000 times in a second. -
@Codex404 You can make array initialized at compile time in some languages like c++ hence it is known how it will be at runtime. In that way I think there will be no cost on runtime.
-
aritzh7527y@okkimus @Codex404 Actually, I will have to rectify, just looking at the assembly (https://godbolt.org/g/jQ1x6H), it looks like the ternary operator requires the least amount of assembly instructions. Would have to do a proper benchmark to know which would be faster in practice, but it is interesting to see how compilers can optimize some things better than others.
-
okkimus17187y@aritzh
Wow that's interesting! Kudos to you.
I actually thought that ternary would be just be syntactic sugar for if-else clause. Never really looked into compilers or C++. -
Also the correct solution is to download a jQuery plugin and do:
console.log($(value).isEven()); -
sugoi6697y@Pogromist x is input variable. Programming is really related to maths(including Algebra). Same as we have variables in algebraic expressions we have variables which change throughout the program.
-
th4t6567yIn this case the best solution is the one that keeps raising the price of RAM, and since I'm poor but moralistic I suggest to optimize it.
Related Rants
Who here is a great programmer?
joke/meme
programming
great programmer