background
i making function receives positive number , rounds number closest integer bellow it.
i have been using math.floor, discovered math.trunc.
i aware both return same value, given positive number, , work in different ways. interested in exploring behavior.
questions
- which 1 faster ?
- which 1 should use?
actually, there more alternative ways remove decimals number. it's tradeoff of readability , speed.
choosing right 1 depends on need. if need remove decimals, use trunc() or bitwise operators.
floor(), ceil() , round() conceptually different trunc().
math library
you know these. use them in standard, non-critical code.
var v = 3.14; [math.trunc(v), math.floor(v), math.ceil(v), math.round(v)] // prints results for different input values these results
t f c r 3.87 : [ 3, 3, 4, 4] 3.14 : [ 3, 3, 4, 3] -3.14 : [-3, -4, -3, -3] -3.87 : [-3, -4, -3, -4] but more fun :)
binary operations , bitwise operators
if @ them in code, might not apparent first glance do, don't use them. though in cases, might useful. example calculating coordinates in <canvas/>. faster, come limitations.
conceptually, work way:
- the operands converted 32-bit integers. (numbers more 32 bits significant bits discarded.)
bitwise logical operators
- each bit in first operand paired corresponding bit in second operand. (first bit first bit, second bit second bit, , on.)
- the operator applied each pair of bits, , result constructed bitwise.
bitwise shift operators
- these operators take
valueshifted ,numberof bit positions shiftvalueby.
however, use 0, zero, false second operand, doesn't original value in these cases:
~ not ~~v
| or v | 0
<< left shift v << 0
>> signed right shift v >> 0
>>> zero-fill right shift v >>> 0
var v = 3.78; [ ~~v , v | 0 , v << 0 , v >> 0 , v >>> 0 ] // prints these results 3.78 : [ 3, 3, 3, 3, 3] 3.14 : [ 3, 3, 3, 3, 3] -3.74 : [-3, -3, -3, -3, 4294967293] -3.14 : [-3, -3, -3, -3, 4294967293]
Comments
Post a Comment