Fix performance issues when an output file is specified

* cache the ordered script file names to avoid expensive recomputations
* only resolve references when absolutely necessary (should only be
right before a compilation call)