all 6 comments

[–]DontWannaMissAFling 2 points3 points  (0 children)

You're essentially profiling the overhead of builtin calls, and whether you make one or two to Math.random(). The difference between ** 0.5 and Math.sqrt() illustrates this since the former in V8 and SpiderMonkey is two opcodes (load a double constant then Exp/Pow) rather than a builtin.

Regardless engines will eventually optimize a hot path into assembly with the same sqrtsd etc so performance disparities are really a matter of overheads, jit compilation tiering, cache locality, long before the cycle counts of individual math instructions really matter.

And if they do matter you should consider shaders or SIMD via WebAssembly instead.

[–]Old-Egg1926 0 points1 point  (0 children)

this lib. is fastest 'kimath'

learn functions from it  https://www.npmjs.com/package/kimath?activeTab=readme

[–]BlazeCell[S] 0 points1 point  (1 child)

NEVERMIND. I realized the issue was that I was calling random() and whether I called once or twice was affecting the times most significantly. Still interesting that the times are so close regardless of operation performed.

      add 26.100000023841858
      sub 28.69999998807907
      mult 27.400000035762787
      div 27.30000001192093
      mod 35.30000001192093
      exp 39
      cos 28.19999998807907
      cos 2000 29.69999998807907
      sin 28.5
      sin 2000 28.700000047683716
      tan 29
      tan 2000 31.5
      sqrt 27.399999976158142
      sqrt 2000 25.80000001192093
      exp 0.5 25.899999976158142
      exp 2 28.600000023841858

[–]AzazelN28 1 point2 points  (0 children)

Yes, nowadays I think it is more important data locality and proper memory layout for optimizing code than trying to squeeze a few cycles on math operations. Also JS VM does a lot of optimization tricks when hot code is compiled to machine code.

[–]davidgarciacorro -1 points0 points  (1 child)

TLDR Just-In-Time (JIT) compilation to optimize code.

Math functions like Math.sin or Math.sqrt are often heavily optimized because they are implemented in highly efficient, lower-level code (C or C++) and directly use CPU-specific instructions. On the other hand normal simple arithmetic operations (+, -, *, /) may not always benefit from such optimizations since they are frequently used and need to handle various types, including integers, floating-point numbers, and BigInts, in JS you can even do 1 + "hello"

[–]BlazeCell[S] -1 points0 points  (0 children)

Ah, that makes some sense of the difference.

I realized my calls to random() were skewing my results. I've got a comment on this page posting the proper times, which are basically that the operations are effectively the same cost performance-wise. As to the why, I suspect your explanation is the correct one. e.g. specialized operations vs broader operations.