Compiler optimizations with broadcast or map

I am not sure how you plan to do that. Also, I don’ t understand why you think that length(data) is “allocated”, there shouldn’t be any allocation.

Generally, the compiler will elide repeated evaluations of functions it considers “pure” (see eg this discussion). You can provide hint for this using Base.@pure, but that is not recommended unless you really know what you are doing. Given that your code has mistakes that would prevent it from working correctly as is (eg data - x instead of data .- x), I am not sure I would suggest pursuing that.

In your example, I don’t think that that repeated calls to length are elided. But length of a vector is a very, very cheap operation, I would not worry about this.