DEV Community

The Mysterious Double Tilde (~~) Operation

Asad Memon on December 06, 2019

Long ago, I was optimizing a hot-path in some game physics code which involved lots of Math.floor() and parseInt() operations. I came across a micr...
Collapse
 
rohansawant profile image
Rohan Sawant

Damn! I had not idea this was a thing!

Thanks for the great read! 🔥

Collapse
 
asadm profile image
Asad Memon

Thanks!

Collapse
 
savagepixie profile image
SavagePixie

That's a very interesting little thing. Do you happen to have any concrete data (or general idea) as to how much it improves performance?

(I'm not trying to contest your point, I'm just curious)

Collapse
 
asadm profile image
Asad Memon

At the time I first found it, I do remember comparing perf and finding it faster.

I just wrote a quick perf test, see the updated article!

Collapse
 
savagepixie profile image
SavagePixie

Cheers! That is a considerable increase from parseInt indeed!

Collapse
 
havespacesuit profile image
Eric Sundquist

It is a good operator if you want a function that truncates toward zero.

Math.floor(-1.6) // -2
~~-1.6 // -1
Collapse
 
barzi profile image
Andy

Amazing article! Thank you

Collapse
 
stevematdavies profile image
Stephen Matthew Davies

I've been using double tilde ocassionally for a while, but I never knew about the single one!

Collapse
 
georgewl profile image
George WL

I think bitwise operations are always a bad idea.

If someone can't read it and guess what it does, then it shouldn't be used.

Collapse
 
asadm profile image
Asad Memon • Edited

You are right. It depends, as I said.

I used it because of perf gains I needed. Maybe a comment explaining the code line would be a good compromise for situations like this.

Collapse
 
lucashogie profile image
Lucas H.

Super interesting! Thank you for the read!

Collapse
 
iam10k profile image
Tyler Encke • Edited

On Firefox, Math.floor is actually faster by 23%.

Firefox Results

Collapse
 
orashus profile image
Rash Edmund Jr

woah,
i'm down for using this.
besides, it's obviously faster.

thank you for this.