Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xpe/0a710c5c0cee3e0d50ef0a9bc3241d3b to your computer and use it in GitHub Desktop.
Save xpe/0a710c5c0cee3e0d50ef0a9bc3241d3b to your computer and use it in GitHub Desktop.
Optimization questions and perhaps an idea

Consider this code. Please pay attention to how .style() derives from element. The rest is not important for the point I'm hoping to make here.

/// Centers `element` horizontally and vertically inside `canvas`.
/// Returns a `Node` struct containing the calculated position and dimensions
/// of the repositioned `element`.
pub fn center_element(element: &HtmlElement, canvas: &Canvas) -> Node {
    let dim = bounding_client_dim(element);
    let pos = centered_pos(&dim, &canvas.dim);
    {
        let style = element.style();
        set_px_property(&style, "left", pos.x);
        set_px_property(&style, "top", pos.y);
    }
    Node { pos, dim }
}

What languages and/or optimization techniques would allow a compiler to know that the usage here of .style() can be optimized?

Here is what I mean. Wouldn't this be nice?... If a caller had already calculated element.style(), then the function above would not need to recalculate it.

Of course, from a compiler's point of view, it must to err on the side of correctness. Perhaps .style() has side effects? Or perhaps .style() might return a different value?

Therefore, in order for a compiler to reuse an previous value from .style(), it would need to reason that no side effects occur AND the value was unchanged.

I'm writing this down because I'm writing a Rust WebAssembly app, and having optimizations like this would make it easier to write efficient and high-level code.

I'm curious. For compiler/language experts who have thought about this, have I captured the essence of the problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment