top | item 43937911

(no title)

tauoverpi | 9 months ago

I forgot to add that "like I don't need to keep asserting that a for-loop counter is an int." is exactly what is happening with a dynamically typed language that is exactly what the runtime ends up doing unless it has a built-in range type to avoid that overhead and the loop variable cannot change while looping. With a static type checker that can be eliminated upfront as the compiler knows that it's an int and not suddenly a string as it's impossible to change the variable's type once it's defined thus all of the overhead of RTTI can be erased.

Javascript has to check on each iteration that the item is an int and for arrays that the length of those arrays hasn't changed underneath along with a bunch of other things as the language doesn't guarantee that it can't change. Even the JIT compiler in use has to check "is this path still that I expect" as at any point the type of the variable used in the loop can change to something else which invalidates the specialization the JIT compiler emitted for the case of it being an int. When you don't use languages with static types you push all of this work on runtime which makes the program slower for every check it needs to do while offering none of the advantages you have with static types.

Thus with a for loop in say C you don't assert that it is an int each time you statically constrain it to be an int as the loop condition can well be based on something else even if int is the more common to use. For example in zig `for` only takes slices and integer ranges with any other type being a compile-error:

    var example: [1 << 8]usize = @splat(0);
    for (&example, 0..) |*num, int| num.* = int;
This is not more work than what you'd do in a dynamically typed language.

discuss

order

No comments yet.