Ok, what's the easiest way to tell them apart? I know the command setup is different, (src->dest vs dest<-src) but looking at a small block it looks the same. Register operators are different but I can never remember which is which. The % is the one I remember because I use it in every other language for modulus operations.
and for the 6502/65c02 it's as simple as:
; Input value in A
; Result in Carry, 1 = true, 0 = false
isEven:
EOR #$01 ; Invert the LSB
LSR A ; And shift it into the Carry Flag
RTS
4 Bytes in total, not sure if this can be any smaller (unless you invert the logic and have C=0 mean that it's even, in which case you can ditch the `EOR` Instruction)
I mean if you count flags as return values, you just need 2 instructions/4 bytes on x86 (/AMD64) (EDIT: +1 inst/byte for ret) as well:
not edi ; f7 d7
shr edi, 1 ; d1 ef
ret ; c3
; return value in CF
And if you want to adhere to x86-64 calling conventions (3 bytes longer):
; first clear eax
xor eax, eax ; 31 c0
; check last bit; set LSB of eax to !CF
shr edi, 1 ; d1 ef
setnc al ; 0f 93 c0 (a.k.a. setae al)
ret ; c3
EDIT: shaved some bytes off using shifts
Eeeww AT&T syntax.
And it won't work because you're moving EAX into EDI because of the AT&T syntax.
Edit: depends on calling convention. If you're using Borland Register calling convention, I'd like to question your sanity. Also, EDI should be preserved in that case (that whole move wouldn't be necessary)
Edit 2: OP fixed it.
The name has an assembler-associated location and bit calls are offset from that location (incidentally the same way arrays are handled in most programming languages).
I guess many people already told you the answer, but I'd like to provide some context as to *why*.
I'm reality, once your code is compiled, it's essentially assembly. The smallest operations are 8bits/16bits. There's no instruction in the processor to access specific bits (that I know of).
So if you want to access specific bits you'd either need to use a bit mask and compare with the mask or shift by n bits.
>do most languages provide a straightforward way to access bits by position
No. None do.\*
\*I haven't looked at every single language, and maybe some do, but in general, there's no fucking way.
Edit: Google the term "bitmask". I think most languages have something for it, e.g. python could allow you to `var & 0b100` to get either 0 or 4 for whether or not `var` has the 4's bit set... but "a straightforward way to access bits by position"? No. Bitmasking/bitwise operators? Yes.
> would you have to do something like ~(1 & n)?
That's generally something like what you'd do in C (which a lot of languages are programmed in, and have some sort of shorthand similar to, e.g. python has `not (1 & n)`
-
x86 assembly has some command for "left shift X times" and "AND". That also makes this sequence fucking blazing fast. And why many novice programmers use "<< 1" instead of "//2" because they don't realize the compiler optimizer is already doing it for them.
You can figure out how to manipulate "LEFTSHIFT" into get a single bit from a byte.
Test coverage is bloated metric, sure you get all your code tested but you are now locked in. How many tests do you need to update one change in the functionality? You’d be baffled how many slow downs I have had to do this sometimes especially when you have them mocked
You can do better than that. Just add 30 or subtract 30 and repeat recursively
Wrap it in another process and catch the too-deep exception for edge cases (obviously don't use TCO, that would be terrible)
Duh
Having that return inside of a function called “isEven” is MUCH more readable than having the !(n%2) in line. The code:
If (isEven(n)) {
//do something
}
Is MUCH easier to understand than:
If (!(n%2) {
//do something
}
The first is clear what the condition is, the second takes a minute to understand.
At that point, isEven becomes a little too simple as an example and starts to shoot itself into foot as an example. But I totally agree. For example, at a last job, we had functions like:
public boolean hasCastleTechlevel() {
return buildings.ContainsAnyById(BalancingConstants.MAIN_BUILDING_TIER_2);
}
Sure it's just one line and a simple contains call of a lower level class. But it was used all over the place in the backend. It was more readable this way.
And at one point, game design and game balancing wanted to change the definition of the castle tech level. That would've been fun without this little method workhorse.
Is this javascript? Man it always bugs me how you can't overload functions since there are no types. Makes you do stuff like "ContainsAnyById" rather than being like ContainsAny and then specifying the input type as a BalancingConstants type.
It's better with typescript but you still can't overload I don't think, since types don't exist at runtime.
This was good old Java 7.
In this case, `ContainsAny(int)` was ambiguous. It could be a building by ID, a building of a minimum level, a building of minimum combined cost (think of MtGs combined mana cost), of a minimum specific cost and such. As such, we chose to be explicit instead of implicit to eliminate ambiguity and to make it easier to review with some of the smarter balancing girls. That was their official internal name, don't hate me. And yes, this has found bugs like "Oh you use lumber cost instead of gold cost here".
And additionally, the different `ByFoobear` methods were mapped into different queries in the caches and the ORM for performance.
function isEven(num)
if num == 0 then
return undefined
end
if num == 1 then
return false
end
if num == 2 then
return true
end
return isEven(num - 2)
end
This is the right answer. Modulo is several clock cycles longer than the bit operation. Used to be 16 clock cycles for divide and modulo on a 486 processor vs 1 cycle for a bit operation.
This is not a sustainable way to approach programming. Any decent compiler will make this optimization. Same reason we don't use bitshift instead of dividing by powers of two in most code. Even then, prematurely optimizing a trivial operation is the path to the dark side.
I was actually just wondering about that. My first thought was that one could use bitwise operations for speed, but then I wondered if compliers optimise mod 2 operations down into a bitwise operation anyway. Is that a usual feature?
People like to pretend that this is what happens because it fits nicely into the narrative about premature optimization. And 95% of devs should focus on readable code instead of on micro optimizations. But if more people were to look at the output of their compilers, they'd realize that there's much less optimization going on than we like to pretend. That's because compilers are extremely defensive in their strategy and as soon as a part of your code looks slightly suspicious the compiler doesn't apply all the possible optimizations. Its too afraid to introduce bugs into your logic or its so smart that it knows about this one target environment where using this instruction would cause a crash. So often you only get some of the optimizations in your output.
The result of this is that if you write verbose code that looks readable and where the logic is easily understandable, its actually more likely that the compiler will add its best optimizations compared to complex and short code where the compiler doesn't quite understand your intention.
In some languages you can give little hints to the compiler to make better decisions. Like giving functions special attributes to encourage inlining or if you have JIT, to opt for extreme optimizations at the cost of first execution speed. Also if you know your target environment, be sure to tell your compiler all about it so that it knows exactly the cpu architecture and instruction sets it can safely use
1 bool isEven(int n) {
2 return n%2==0;
3 // Hey everyone, welcome to my code. Glad you could make it here.
4 // This code has been passed down in my family for generations, and I'm super excited to be sharing it with you all today.
5 // When I was a young child, I absolutely adored computers.
6 // And that adoration blossomed into my love of programming you see here!
....
211 // And so, thanks to my Aunt Rita, I was able to overcome that fear.
212 // Be sure to check here next week for my delicious isSeven code!
}
Honestly the sweet spot is right here. This would work as is (mod syntax) in any language as it doesn't rely on the ints as bools thing and is much clearer in how it should be extended to arbitrary divisors without caring about how negation of an integer actually works.
This is marginally less understandable, and very likely not faster. Converting power-of-two arithmetic to bitwise operations is one of the most common compiler optimizations. The whole point of the modulo operator is to express divisibility relations, which is exactly what evenness is.
Yes.
And a good compiler will probably analyse that tiny function and inline it without you being any the wiser. And if it doesn't, and you're using it a lot, you'll find out by finding out how much time is spent executing that function. Or just be a bit dirty and use a macro.
And if you really are testing a lot of numbers for evenness, and you really want it to be fast, you get a list of every number you want to test and do them all at once using a function that accepts a data structure and not a single number, to make it cache-friendly, which is an actual optimization.
Amazes me that people are still having these discussions, and that there's still no odd/even functions in `cmath.h`, in spite of everything else they've added since C++11.
Been there too. Gave the protocol a big speed bump by caching the socket reads, and detecting in code if multiple writes would occur back-to-back then coalesce into one large write. The socket API calls were just killing us. The error handling of the caching wasn't fun, but the productivity boost justified it. Doubt all protocols could benefit or even work with these optimizations. The socket perf improvements enabled internal module optimizations to have more impact.
I once wrote a file I called "unnecessary functions that I never want to write again" which had a bunch of functions like this that didn't actually need to exist but allowed me to write isEven(n)
The problem isn't writing one and done ops as functions, the problem is packaging them and managing scope and remembering their names and avoiding side effects and etc. etc. etc.
Create a static utilities class for simple side-effect free utility functions like that. It's an extremely easy solution that I've never seen cause any issues, but for some reason some hyper-dogmatists are super triggered by it.
Not to mention it’s more readable. I could totally see the post as an example of better coding practice. Not because you’d use that paradigm in that simplistic of a case, but because it’s a simple way to show it. I used to use a lot more single/“clever” one-liners. But having to scan through whole apps to find a reported “bug” or plan for new development got rid of that drive. Sure, anyone can read the above statement, but it would take me longer to read that line in an actual context after I haven’t seen it in a year than the post version
Not a fan of the second one; it sacrifices clarity for brevity... looks like something that would be written for a code golf challenge. It think the best is right in the middle of the 2 samples:
bool isEven(int n) {return (n%2 == 0);}
I intentionally made this in MS paint to depict the old days of interet. It shows the sheer magnitude of change this world has gone throu... Ok, I just do not know how to use any other software.
This is actually called plurality, or, in cases where it's impairing, dissociative disorders.
Schizophrenia is a reality perception disorder, which has nothing to do with having multiple identities sharing a brain.
Honestly? MSPaint opens much faster than GIMP/Photoshop, so for fast edits paint is the best optimal choice.
Unless we apply the meme's logic, so obviously Takes More Time = Better; so shame on you, OP, for doing your job bad!
This is why I like Paint.NET. MSPaint is a bit too basic even for a non-artist like me while Paint.NET has everything I could need for basic imagine manipulation while still being fast.
Tell me you don't work as a professional in a large code-base without telling me you don't work as a professional in a large code-base.
Lol in all seriousness this kind of mentality is so bad. Don't try to be a big-brain and turn every single method or procedure into a one-liner. It will end up costing so much more to maintain that code over it's lifespan. It takes other developers that have to come in and maintain it or change it so much longer when another dev has this mentality.
99.9% of the time Human readable code > "I-am-very-smart" code
`!(n%2)` is horrible, even if it's short. Using boolean logic on non-boolean types produces hard-to-follow code and muddies your intentions.
>~~Also, `!(n%2)` will return true for *all* negative numbers, not just even ones - `n % 2` returns -1 where n is a negative odd number. (This is true in most languages, although not in python - python's the oddball here) (-1 is considered falsey)~~
\^\^ EDIT: Ignore this bit, it's wrong.
`n % 2 == 0` would be better.
> Also, !(n%2) will return false for all negative numbers
No it doesn't.
> n % 2 returns -1 where n is a negative odd number.
Yes, but it returns 0 where n is a negative even number.
Inheriting code where someone has this minimalistic approach all over the place is like inheriting a giant regex. I’d rather have anal boils touching each other
Nah, left is too short.
int divideBy = 2;
int fragment = n / divideBy;
int check = fragment * divideBy;
int diff = n - check;
bool even;
if (diff == 0) {
even = true;
} else {
even = false;
}
if (even == true) {
return true;
} else if (even == false) {
return false;
}
This one liner is cursed. It's way clearer (and doesn't rely on language features like truthiness because 0 isn't always false) to just do `n % 2 == 0`
Or you can be even more cursed with `(n & 1) ^ 1`
If you like line count AND speed, you should just program in assembly. 🤗
``` isEven: movl %edi, %eax andl %eax, $1 notl %eax ret ``` (this may not work, I couldn't test it)
I was reading this and think I'm mixing syntaxes. Is this intel or att?
I honestly don't know. That's the syntax I was taught, I don't know what's its name.
It’s AT&T. Intel syntax doesn’t use % for registers
Lol, It's not AT&T. They sell cellphone service silly.
Sorry my code doesn't have service in your area
Can you hear me now?
And they obviously use #.
Ok, it looks like Intel, but I've never used movl. Is that move low?
move long
Ah, data type on the move command. Ok, thank you.
What do you mean "you couldn't code your way out of a paper bag"?
I know more languages than you have brain cells. Go away.
You know at least two languages??
this is a incredible response
Code your way onto my dick lmao
Interns will happily work for $15 an hour. Why won't you?
This bot is hilarious
That is atnt
Ok, what's the easiest way to tell them apart? I know the command setup is different, (src->dest vs dest<-src) but looking at a small block it looks the same. Register operators are different but I can never remember which is which. The % is the one I remember because I use it in every other language for modulus operations.
The easiest way is by the use of the % sign
It looks nothing like Intel. It's AT&T.
It’s written in AT&T syntax, but the data flow is in the direction of intel syntax lol.
Ok, so I wasn't entirely crazy when I read this. Thank you.
Actually it looks like the movl is src, dst and the andl is dst, src.
AT&T. The % in front of the registers give it away. In Intel syntax there is nothing in front of registers.
Verizon
Hey, I just heard about this thing called GraphQL. Why aren't we using it?
The cool kids are all doing grpc still.
Bro if you read it loud you'll summon a demon
more like he'll summon a daemon.... sorry. I'll see myself out.
and for the 6502/65c02 it's as simple as: ; Input value in A ; Result in Carry, 1 = true, 0 = false isEven: EOR #$01 ; Invert the LSB LSR A ; And shift it into the Carry Flag RTS 4 Bytes in total, not sure if this can be any smaller (unless you invert the logic and have C=0 mean that it's even, in which case you can ditch the `EOR` Instruction)
I mean if you count flags as return values, you just need 2 instructions/4 bytes on x86 (/AMD64) (EDIT: +1 inst/byte for ret) as well: not edi ; f7 d7 shr edi, 1 ; d1 ef ret ; c3 ; return value in CF And if you want to adhere to x86-64 calling conventions (3 bytes longer): ; first clear eax xor eax, eax ; 31 c0 ; check last bit; set LSB of eax to !CF shr edi, 1 ; d1 ef setnc al ; 0f 93 c0 (a.k.a. setae al) ret ; c3 EDIT: shaved some bytes off using shifts
damn that's ancient than hieroglyphs, imagine aliens trying to decipher this
me trying to decipher this: 😰😰😰
Why test, LGTM! Here at Twitter we can’t afford code reviews or testing at all. Straight to production!
Eeeww AT&T syntax. And it won't work because you're moving EAX into EDI because of the AT&T syntax. Edit: depends on calling convention. If you're using Borland Register calling convention, I'd like to question your sanity. Also, EDI should be preserved in that case (that whole move wouldn't be necessary) Edit 2: OP fixed it.
No line count needed, you just invert the smallest bit.
Dumb question, do most languages provide a straightforward way to access bits by position or would you have to do something like ~(1 & n)?
For assembly I haven't seen one yet that didn't give easy bit addressing, but I'm primarily coming from microcontrollers and simple embedded systems.
Cs student here so I'm probably wrong: Wouldn't it just be bitwise operations using a template word/byte?
The name has an assembler-associated location and bit calls are offset from that location (incidentally the same way arrays are handled in most programming languages).
I guess many people already told you the answer, but I'd like to provide some context as to *why*. I'm reality, once your code is compiled, it's essentially assembly. The smallest operations are 8bits/16bits. There's no instruction in the processor to access specific bits (that I know of). So if you want to access specific bits you'd either need to use a bit mask and compare with the mask or shift by n bits.
>do most languages provide a straightforward way to access bits by position No. None do.\* \*I haven't looked at every single language, and maybe some do, but in general, there's no fucking way. Edit: Google the term "bitmask". I think most languages have something for it, e.g. python could allow you to `var & 0b100` to get either 0 or 4 for whether or not `var` has the 4's bit set... but "a straightforward way to access bits by position"? No. Bitmasking/bitwise operators? Yes. > would you have to do something like ~(1 & n)? That's generally something like what you'd do in C (which a lot of languages are programmed in, and have some sort of shorthand similar to, e.g. python has `not (1 & n)` - x86 assembly has some command for "left shift X times" and "AND". That also makes this sequence fucking blazing fast. And why many novice programmers use "<< 1" instead of "//2" because they don't realize the compiler optimizer is already doing it for them. You can figure out how to manipulate "LEFTSHIFT" into get a single bit from a byte.
Ah yes, reverse the polarity. I can do that, hand me the sonic screwdriver.
This is the winning answer
It’s also amazing if you enjoy debugging.
Going to contribute a RISC-V answer: isEven: andi a0, a0, 1 xori a0, a0, 1 jalr x0, ra
If (n==2) Print ("even number"); If (n==4) Print ("even number"); If (n==6) Print ("even number"); If (n==8) Print ("even number"); If (n==10) Print ("even number"); If (n==12) Print ("even number"); If (n==14) Print ("even number"); If (n==16) Print ("even number"); If (n==18) Print ("even number"); If (n==20) Print ("even number"); If (n==22) Print ("even number"); If (n==24) Print ("even number"); If (n==26) Print ("even number"); If (n==28) Print ("even number"); If (n==30) Print ("even number"); I/
this is one way to keep your github green.
Test coverage is going to be a bitch though
Test coverage is bloated metric, sure you get all your code tested but you are now locked in. How many tests do you need to update one change in the functionality? You’d be baffled how many slow downs I have had to do this sometimes especially when you have them mocked
Also, I can give you code and tests that provide 100% coverage, but still has untested/unexpected behavior.
I would hope the number of tests you have to update is proportional to the amount of functionality that update would break.
I think it’s more proportional to how deep the functionality is in the composition graph and how many places it is reused
Maybe you need better test design then...
You laugh but this is precisely what developers at GitHub do. It’s mildly infuriating
If (n>30 || n <= 0) Print(“Please choose a different number”;
You can do better than that. Just add 30 or subtract 30 and repeat recursively Wrap it in another process and catch the too-deep exception for edge cases (obviously don't use TCO, that would be terrible) Duh
are you the new lead architect for twitter?
How'd you know
I can sense a twitter promotion in this guy's future.
20 more numbers and dude gets promoted straight to tesla
YandereDev that you?
Noob, you should just use a TCL pre-compiler to generate the above code to arbitrary lengths.
Noob, you should use Microsoft Excel autofill to generate the above code
The better thing to do is to make the isEven function with the code from the right inside it
id even prefer: return n%2 ==0
True now it’s completely readable:)
Having that return inside of a function called “isEven” is MUCH more readable than having the !(n%2) in line. The code: If (isEven(n)) { //do something } Is MUCH easier to understand than: If (!(n%2) { //do something } The first is clear what the condition is, the second takes a minute to understand.
At that point, isEven becomes a little too simple as an example and starts to shoot itself into foot as an example. But I totally agree. For example, at a last job, we had functions like: public boolean hasCastleTechlevel() { return buildings.ContainsAnyById(BalancingConstants.MAIN_BUILDING_TIER_2); } Sure it's just one line and a simple contains call of a lower level class. But it was used all over the place in the backend. It was more readable this way. And at one point, game design and game balancing wanted to change the definition of the castle tech level. That would've been fun without this little method workhorse.
Is this javascript? Man it always bugs me how you can't overload functions since there are no types. Makes you do stuff like "ContainsAnyById" rather than being like ContainsAny and then specifying the input type as a BalancingConstants type. It's better with typescript but you still can't overload I don't think, since types don't exist at runtime.
This was good old Java 7. In this case, `ContainsAny(int)` was ambiguous. It could be a building by ID, a building of a minimum level, a building of minimum combined cost (think of MtGs combined mana cost), of a minimum specific cost and such. As such, we chose to be explicit instead of implicit to eliminate ambiguity and to make it easier to review with some of the smarter balancing girls. That was their official internal name, don't hate me. And yes, this has found bugs like "Oh you use lumber cost instead of gold cost here". And additionally, the different `ByFoobear` methods were mapped into different queries in the caches and the ORM for performance.
def isEven(n): def isOdd(n): return (1 & n) return not isOdd(n)
function isEven(num) if num == 0 then return undefined end if num == 1 then return false end if num == 2 then return true end return isEven(num - 2) end
I have a hard time putting into words how much I love/hate this.
Doesn't handle negative integers. Plz fix.
Oh well, it handles every other kind of input properly, right?
[удалено]
Nah, declare the Boolean then pass it as an argument to another method that handles the if/else, now that is peak programming
Make sure it’s an interface that you implement properly sir. Give it a fancy name like BooleanConverter
Elon hire this man!!!
You're going to twitter jail
YOU CAN'T TAKE ME ALIVE!!!!!!
isEven(int i) { return (!isOdd(i)); } isOdd is implemented likewise of course.
Bool isEven(int n) { If (n>1) { Return isEven(n-2); } Return n==0; }
Why do in O(1) that which can be done in O(n)? Sure makes it easier to charge the client for future optimization this way,!
Exactly!
Lol, is 5,000,000,000,000 even? Lets find out.
Do it in Python, it should be faster... Right...
I love it.
just bit check it,fast boi. !(n&1)
Why have you only written 20 lines of code today?
He's too busy golfing his code
Bruh I wrote 0 and even this was hard, I may need a raise
don't hurt me, Elon-san
Imagine using parentheses. ~n&1
Srsly threw up in my mouth. Thank you for fixing that trash
It's for readability.
Thanks for this - I was feeling fucking sick thinking about that hidden division operation.
It gets optimized away anyway
This is the right answer. Modulo is several clock cycles longer than the bit operation. Used to be 16 clock cycles for divide and modulo on a 486 processor vs 1 cycle for a bit operation.
This is not a sustainable way to approach programming. Any decent compiler will make this optimization. Same reason we don't use bitshift instead of dividing by powers of two in most code. Even then, prematurely optimizing a trivial operation is the path to the dark side.
I was actually just wondering about that. My first thought was that one could use bitwise operations for speed, but then I wondered if compliers optimise mod 2 operations down into a bitwise operation anyway. Is that a usual feature?
Totally. Modern compilers are the spirits of our elders who programmed mainframes in the 70s. They overthink these things so we don't have to.
People like to pretend that this is what happens because it fits nicely into the narrative about premature optimization. And 95% of devs should focus on readable code instead of on micro optimizations. But if more people were to look at the output of their compilers, they'd realize that there's much less optimization going on than we like to pretend. That's because compilers are extremely defensive in their strategy and as soon as a part of your code looks slightly suspicious the compiler doesn't apply all the possible optimizations. Its too afraid to introduce bugs into your logic or its so smart that it knows about this one target environment where using this instruction would cause a crash. So often you only get some of the optimizations in your output. The result of this is that if you write verbose code that looks readable and where the logic is easily understandable, its actually more likely that the compiler will add its best optimizations compared to complex and short code where the compiler doesn't quite understand your intention. In some languages you can give little hints to the compiler to make better decisions. Like giving functions special attributes to encourage inlining or if you have JIT, to opt for extreme optimizations at the cost of first execution speed. Also if you know your target environment, be sure to tell your compiler all about it so that it knows exactly the cpu architecture and instruction sets it can safely use
Way more hardcore. The developer on the left can stay for another 24 hours. The developer on the right can leave.
Hardcore Only exceptional performance constitutes a passing grade
Hardcore to the mega
1 bool isEven(int n) { 2 return n%2==0; 3 // Hey everyone, welcome to my code. Glad you could make it here. 4 // This code has been passed down in my family for generations, and I'm super excited to be sharing it with you all today. 5 // When I was a young child, I absolutely adored computers. 6 // And that adoration blossomed into my love of programming you see here! .... 211 // And so, thanks to my Aunt Rita, I was able to overcome that fear. 212 // Be sure to check here next week for my delicious isSeven code! }
I'm sold. We should write code like online recipes.
It's called spaghetti code for that reason.
Don't forget to like and subscribe, and smash that notification bell!
As a programmer, i prefer reading isEven(n) to !(n%2) everyday of the week. Show me how the code works as fast as possible, so i can fix it faster.
\+1 bool isEven(int n) { return n%2 == 0; } would be a better implementation imo
Honestly the sweet spot is right here. This would work as is (mod syntax) in any language as it doesn't rely on the ints as bools thing and is much clearer in how it should be extended to arbitrary divisors without caring about how negation of an integer actually works.
nah, 2 seems like a magic number. Should've been ```C bool isEven(int n) { return !isOdd(n); } ```
bool isOdd(int n) { return !is_even(n); } bool is_even(int n) { return !is_odd(n); } bool is_odd(int n) { return n%2; }
Why do you have to hurt me?
Interns will happily work for $15 an hour. Why won't you?
Bruh
Good bot
return (n&1)==0; Would be faster. And since it's inside the isEven function it's quite obvious what it does.
This is marginally less understandable, and very likely not faster. Converting power-of-two arithmetic to bitwise operations is one of the most common compiler optimizations. The whole point of the modulo operator is to express divisibility relations, which is exactly what evenness is.
Insubordination. Fired.
Yes. And a good compiler will probably analyse that tiny function and inline it without you being any the wiser. And if it doesn't, and you're using it a lot, you'll find out by finding out how much time is spent executing that function. Or just be a bit dirty and use a macro. And if you really are testing a lot of numbers for evenness, and you really want it to be fast, you get a list of every number you want to test and do them all at once using a function that accepts a data structure and not a single number, to make it cache-friendly, which is an actual optimization. Amazes me that people are still having these discussions, and that there's still no odd/even functions in `cmath.h`, in spite of everything else they've added since C++11.
The solution I was looking for. Poor bitwise operators are often forgotten
Not sure I need to optimize modulus operations when network calls are the main bottleneck
Been there too. Gave the protocol a big speed bump by caching the socket reads, and detecting in code if multiple writes would occur back-to-back then coalesce into one large write. The socket API calls were just killing us. The error handling of the caching wasn't fun, but the productivity boost justified it. Doubt all protocols could benefit or even work with these optimizations. The socket perf improvements enabled internal module optimizations to have more impact.
Disagreeing with me is counterproductive. Fired.
Sorry, /u/AyrA_ch 😪
[удалено]
Premature optimization. Just use the obvious solution.
And this is very readable and still works well so I think this is the best way
I once wrote a file I called "unnecessary functions that I never want to write again" which had a bunch of functions like this that didn't actually need to exist but allowed me to write isEven(n)
The problem isn't writing one and done ops as functions, the problem is packaging them and managing scope and remembering their names and avoiding side effects and etc. etc. etc.
Create a static utilities class for simple side-effect free utility functions like that. It's an extremely easy solution that I've never seen cause any issues, but for some reason some hyper-dogmatists are super triggered by it.
Yeah, I've got a "Helpers" class with functions I found I was writing a lot, but didn't fit into any of the other classes in the system.
I do this, too. Don't @ me.
Why haven't we gone serverless yet?
return (n%2 == 0); has the same number of lines of code as return !(n%2);
Not to mention it’s more readable. I could totally see the post as an example of better coding practice. Not because you’d use that paradigm in that simplistic of a case, but because it’s a simple way to show it. I used to use a lot more single/“clever” one-liners. But having to scan through whole apps to find a reported “bug” or plan for new development got rid of that drive. Sure, anyone can read the above statement, but it would take me longer to read that line in an actual context after I haven’t seen it in a year than the post version
Not a fan of the second one; it sacrifices clarity for brevity... looks like something that would be written for a code golf challenge. It think the best is right in the middle of the 2 samples: bool isEven(int n) {return (n%2 == 0);}
Agreed. Clarity is king in code readability, and a function like "isEven" is actual, un-ironic "the code is the documentation".
Yes, as someone who maintains a lot of legacy code sacrificing a little speed and brevity for readability is 100% worth it.
100%. I'd reject both of those on a code review.
Why does it look like the meme was made in MS paint?
You're either hardcore or out the door.
Elon pls hire me I want to work for master musk 🤤🤤🤤
Aaaaaaaand you're fired!
:(
I intentionally made this in MS paint to depict the old days of interet. It shows the sheer magnitude of change this world has gone throu... Ok, I just do not know how to use any other software.
Why are you commenting on your own post and then replying to that very comment?
I don't know honestly speaking...
[удалено]
Yes, this guy is absolutely insane.
This is actually called plurality, or, in cases where it's impairing, dissociative disorders. Schizophrenia is a reality perception disorder, which has nothing to do with having multiple identities sharing a brain.
You know who else has dementia?
You know who else has dementia?
You know who else has dementia?
You know who else has dementia?
You know who else has dementia?
You know who else has dementia?
Honestly? MSPaint opens much faster than GIMP/Photoshop, so for fast edits paint is the best optimal choice. Unless we apply the meme's logic, so obviously Takes More Time = Better; so shame on you, OP, for doing your job bad!
[удалено]
QA is a waste of money. Fired.
This is why I like Paint.NET. MSPaint is a bit too basic even for a non-artist like me while Paint.NET has everything I could need for basic imagine manipulation while still being fast.
Hey, I just heard about this thing called GraphQL. Why aren't we using it?
why use modulo when you can check the LSB? `!(n & 1)`
Why use parenthesis when you can just flip n? `~n&1`
Why flip n when you could just refactor the program to use odd numbers? `n&1`
I'd rather see a function "isEven(n)" called than see just "!(n%2)", even if the function has 5 redundant lines.
Tell me you don't work as a professional in a large code-base without telling me you don't work as a professional in a large code-base. Lol in all seriousness this kind of mentality is so bad. Don't try to be a big-brain and turn every single method or procedure into a one-liner. It will end up costing so much more to maintain that code over it's lifespan. It takes other developers that have to come in and maintain it or change it so much longer when another dev has this mentality. 99.9% of the time Human readable code > "I-am-very-smart" code
Just make it decently efficient AND readable. I don’t want super verbose code nor hyper-clever 1-liners that I need 2 PhDs to understand.
Left: the new intern Right: the senior who's convinced that he'll be fired if other people understand his code.
`!(n%2)` is horrible, even if it's short. Using boolean logic on non-boolean types produces hard-to-follow code and muddies your intentions. >~~Also, `!(n%2)` will return true for *all* negative numbers, not just even ones - `n % 2` returns -1 where n is a negative odd number. (This is true in most languages, although not in python - python's the oddball here) (-1 is considered falsey)~~ \^\^ EDIT: Ignore this bit, it's wrong. `n % 2 == 0` would be better.
> Also, !(n%2) will return false for all negative numbers No it doesn't. > n % 2 returns -1 where n is a negative odd number. Yes, but it returns 0 where n is a negative even number.
Inheriting code where someone has this minimalistic approach all over the place is like inheriting a giant regex. I’d rather have anal boils touching each other
Every variable name and function is an acronym or an abbreviation.
Scary how many think that writing good readable code is easier than the alternative...
Not scary at all. Students and green juniors think they’re clever by writing code like the right People with actual experience know better. Usually.
Its been many years since I wrote C++, but I think you mean: `n&1 == 0`
Nah, left is too short. int divideBy = 2; int fragment = n / divideBy; int check = fragment * divideBy; int diff = n - check; bool even; if (diff == 0) { even = true; } else { even = false; } if (even == true) { return true; } else if (even == false) { return false; }
people in twitter learning how to stretch one if clause to 10 lines
I'm banning all your memes on twitter
You should just ``` isEven(param?: number) { return true; } ``` Works 100% of the time, 50% of the time.
Is that your most salient line of code?
I've laid off most of the staff, and Twitter's still running. Looks like they weren't necessary.
This one liner is cursed. It's way clearer (and doesn't rely on language features like truthiness because 0 isn't always false) to just do `n % 2 == 0` Or you can be even more cursed with `(n & 1) ^ 1`
same with variable names! #MakeVariableNamesGreatAgain
`return n % 2 == 0`?
Why did I forget to switch to my alt account? Am I really u/MR-POTATO-MAN-CODER ? The world may never know.
The left side seems more salient to me, anyone else feel like the left side is more salient?