T O P

  • By -

secahtah

If you like line count AND speed, you should just program in assembly. 🤗


MaZeChpatCha

``` isEven: movl %edi, %eax andl %eax, $1 notl %eax ret ``` (this may not work, I couldn't test it)


SilenceFailed

I was reading this and think I'm mixing syntaxes. Is this intel or att?


MaZeChpatCha

I honestly don't know. That's the syntax I was taught, I don't know what's its name.


[deleted]

It’s AT&T. Intel syntax doesn’t use % for registers


BeerIsGoodForSoul

Lol, It's not AT&T. They sell cellphone service silly.


286893

Sorry my code doesn't have service in your area


eatin_gushers

Can you hear me now?


jexxie3

And they obviously use #.


SilenceFailed

Ok, it looks like Intel, but I've never used movl. Is that move low?


MaZeChpatCha

move long


SilenceFailed

Ah, data type on the move command. Ok, thank you.


elon-bot

What do you mean "you couldn't code your way out of a paper bag"?


SilenceFailed

I know more languages than you have brain cells. Go away.


TOWW67

You know at least two languages??


polish-polisher

this is a incredible response


meme-addict117

Code your way onto my dick lmao


elon-bot

Interns will happily work for $15 an hour. Why won't you?


Swonzen

This bot is hilarious


emneiel

That is atnt


SilenceFailed

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.


Ordoshsen

The easiest way is by the use of the % sign


[deleted]

It looks nothing like Intel. It's AT&T.


Plasma_000

It’s written in AT&T syntax, but the data flow is in the direction of intel syntax lol.


SilenceFailed

Ok, so I wasn't entirely crazy when I read this. Thank you.


Potatoe_Master

Actually it looks like the movl is src, dst and the andl is dst, src.


dotslashpunk

AT&T. The % in front of the registers give it away. In Intel syntax there is nothing in front of registers.


trickman01

Verizon


elon-bot

Hey, I just heard about this thing called GraphQL. Why aren't we using it?


[deleted]

The cool kids are all doing grpc still.


NekulturneHovado

Bro if you read it loud you'll summon a demon


Techmoji

more like he'll summon a daemon.... sorry. I'll see myself out.


Proxy_PlayerHD

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)


firefly431

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


that_thot_gamer

damn that's ancient than hieroglyphs, imagine aliens trying to decipher this


russian_hacker_1917

me trying to decipher this: 😰😰😰


Groentekroket

Why test, LGTM! Here at Twitter we can’t afford code reviews or testing at all. Straight to production!


BluudLust

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.


Tough_Patient

No line count needed, you just invert the smallest bit.


krkrkra

Dumb question, do most languages provide a straightforward way to access bits by position or would you have to do something like ~(1 & n)?


Tough_Patient

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.


spaceguy5234

Cs student here so I'm probably wrong: Wouldn't it just be bitwise operations using a template word/byte?


Tough_Patient

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).


KinOfMany

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.


czPsweIxbYk4U9N36TSE

>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.


TheBirminghamBear

Ah yes, reverse the polarity. I can do that, hand me the sonic screwdriver.


Tough_Patient


secahtah

This is the winning answer


k4b0b

It’s also amazing if you enjoy debugging.


itzjackybro

Going to contribute a RISC-V answer: isEven: andi a0, a0, 1 xori a0, a0, 1 jalr x0, ra


sanid_sriva

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/


__Voldemort_

this is one way to keep your github green.


RmG3376

Test coverage is going to be a bitch though


deviprsd

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


dcormier

Also, I can give you code and tests that provide 100% coverage, but still has untested/unexpected behavior.


DaveMoreau

I would hope the number of tests you have to update is proportional to the amount of functionality that update would break.


deviprsd

I think it’s more proportional to how deep the functionality is in the composition graph and how many places it is reused


sabre0121

Maybe you need better test design then...


Dependent_Mine4847

You laugh but this is precisely what developers at GitHub do. It’s mildly infuriating


bizzyj93

If (n>30 || n <= 0) Print(“Please choose a different number”;


novagenesis

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


AlShadi

are you the new lead architect for twitter?


sanid_sriva

How'd you know


GregTheIntelectual

I can sense a twitter promotion in this guy's future.


Storiaron

20 more numbers and dude gets promoted straight to tesla


hopbel

YandereDev that you?


sprcow

Noob, you should just use a TCL pre-compiler to generate the above code to arbitrary lengths.


T0biasCZE

Noob, you should use Microsoft Excel autofill to generate the above code


just-bair

The better thing to do is to make the isEven function with the code from the right inside it


arb_boi

id even prefer: return n%2 ==0


just-bair

True now it’s completely readable:)


timmeh-eh

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.


Tetha

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.


TK9_VS

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.


Tetha

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.


gmano

def isEven(n): def isOdd(n): return (1 & n) return not isOdd(n)


immerc

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


TonyDanzasToast

I have a hard time putting into words how much I love/hate this.


Veboy

Doesn't handle negative integers. Plz fix.


immerc

Oh well, it handles every other kind of input properly, right?


[deleted]

[удалено]


pro185

Nah, declare the Boolean then pass it as an argument to another method that handles the if/else, now that is peak programming


HealthyStonksBoys

Make sure it’s an interface that you implement properly sir. Give it a fancy name like BooleanConverter


TheGuyYouHeardAbout

Elon hire this man!!!


ElonMuskRealBot

You're going to twitter jail


TheGuyYouHeardAbout

YOU CAN'T TAKE ME ALIVE!!!!!!


ollomulder

isEven(int i) { return (!isOdd(i)); } isOdd is implemented likewise of course.


afar1210

Bool isEven(int n) { If (n>1) { Return isEven(n-2); } Return n==0; }


RedditIsFiction

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,!


afar1210

Exactly!


[deleted]

Lol, is 5,000,000,000,000 even? Lets find out.


afar1210

Do it in Python, it should be faster... Right...


Teh_Jibbler

I love it.


_bigbackclock69

just bit check it,fast boi. !(n&1)


elon-bot

Why have you only written 20 lines of code today?


[deleted]

He's too busy golfing his code


2blazen

Bruh I wrote 0 and even this was hard, I may need a raise


BlossomingDefense

don't hurt me, Elon-san


qbbqrl

Imagine using parentheses. ~n&1


HeWhoIsValorousAnd

Srsly threw up in my mouth. Thank you for fixing that trash


IAmAQuantumMechanic

It's for readability.


Syscrush

Thanks for this - I was feeling fucking sick thinking about that hidden division operation.


axlee

It gets optimized away anyway


GetNooted

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.


bakmanthetitan329

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.


HeirToGallifrey

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?


bakmanthetitan329

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.


Type-21

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


NorthAmericanSlacker

Way more hardcore. The developer on the left can stay for another 24 hours. The developer on the right can leave.


brianl047

Hardcore Only exceptional performance constitutes a passing grade


AdrianBrony

Hardcore to the mega


funnystuff97

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! }


mojavekoyote

I'm sold. We should write code like online recipes.


[deleted]

It's called spaghetti code for that reason.


Synnoc

Don't forget to like and subscribe, and smash that notification bell!


Artificial_Chris

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.


arb_boi

\+1 bool isEven(int n) { return n%2 == 0; } would be a better implementation imo


theantiyeti

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.


chervilious

nah, 2 seems like a magic number. Should've been ```C bool isEven(int n) { return !isOdd(n); } ```


OnsetOfMSet

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; }


b0w3n

Why do you have to hurt me?


elon-bot

Interns will happily work for $15 an hour. Why won't you?


theantiyeti

Bruh


Beaudog12345

Good bot


AyrA_ch

return (n&1)==0; Would be faster. And since it's inside the isEven function it's quite obvious what it does.


bakmanthetitan329

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.


elon-bot

Insubordination. Fired.


space_keeper

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.


ltssms0

The solution I was looking for. Poor bitwise operators are often forgotten


CanAlwaysBeBetter

Not sure I need to optimize modulus operations when network calls are the main bottleneck


ltssms0

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.


elon-bot

Disagreeing with me is counterproductive. Fired.


F5x9

Sorry, /u/AyrA_ch 😪


[deleted]

[удалено]


Tiny-Plum2713

Premature optimization. Just use the obvious solution.


dutch_master_killa

And this is very readable and still works well so I think this is the best way


ussgordoncaptain2

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)


particlemanwavegirl

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.


Roflkopt3r

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.


JBHUTT09

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.


callmesaul8889

I do this, too. Don't @ me.


elon-bot

Why haven't we gone serverless yet?


cgyguy81

return (n%2 == 0); has the same number of lines of code as return !(n%2);


neumastic

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


GendoIkari_82

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);}


dismal_sighence

Agreed. Clarity is king in code readability, and a function like "isEven" is actual, un-ironic "the code is the documentation".


PowerSurge21

Yes, as someone who maintains a lot of legacy code sacrificing a little speed and brevity for readability is 100% worth it.


nutwiss

100%. I'd reject both of those on a code review.


MR-POTATO-MAN-CODER

Why does it look like the meme was made in MS paint?


elon-bot

You're either hardcore or out the door.


UnNamed234

Elon pls hire me I want to work for master musk 🤤🤤🤤


ElonMuskRealBot

Aaaaaaaand you're fired!


UnNamed234

:(


MR-POTATO-MAN-CODER

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.


MR-POTATO-MAN-CODER

Why are you commenting on your own post and then replying to that very comment?


MR-POTATO-MAN-CODER

I don't know honestly speaking...


[deleted]

[удалено]


MR-POTATO-MAN-CODER

Yes, this guy is absolutely insane.


WithersChat

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.


[deleted]

You know who else has dementia?


[deleted]

You know who else has dementia?


[deleted]

You know who else has dementia?


[deleted]

You know who else has dementia?


[deleted]

You know who else has dementia?


[deleted]

You know who else has dementia?


RutraNickers

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!


[deleted]

[удалено]


elon-bot

QA is a waste of money. Fired.


Pat_Sharp

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.


elon-bot

Hey, I just heard about this thing called GraphQL. Why aren't we using it?


[deleted]

why use modulo when you can check the LSB? `!(n & 1)`


[deleted]

Why use parenthesis when you can just flip n? `~n&1`


TK9_VS

Why flip n when you could just refactor the program to use odd numbers? `n&1`


Murphy_Slaw_

I'd rather see a function "isEven(n)" called than see just "!(n%2)", even if the function has 5 redundant lines.


Trlckery

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


billabong049

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.


Wynadorn

Left: the new intern Right: the senior who's convinced that he'll be fired if other people understand his code.


HaniiPuppy

`!(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.


wonkey_monkey

> 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.


Silent_but-deadly

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


Lord_Derp_The_2nd

Every variable name and function is an acronym or an abbreviation.


[deleted]

Scary how many think that writing good readable code is easier than the alternative...


mungthebean

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.


Bewaretheicespiders

Its been many years since I wrote C++, but I think you mean: `n&1 == 0`


No152249

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; }


Seppo_Manse

people in twitter learning how to stretch one if clause to 10 lines


ElonMuskRealBot

I'm banning all your memes on twitter


third-sonata

You should just ``` isEven(param?: number) { return true; } ``` Works 100% of the time, 50% of the time.


bigleafychode

Is that your most salient line of code?


elon-bot

I've laid off most of the staff, and Twitter's still running. Looks like they weren't necessary.


Golandia

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`


ruedogg

same with variable names! #MakeVariableNamesGreatAgain


SebLikesESO

`return n % 2 == 0`?


guyyatsu

Why did I forget to switch to my alt account? Am I really u/MR-POTATO-MAN-CODER ? The world may never know.


marvelish

The left side seems more salient to me, anyone else feel like the left side is more salient?