Skip to content

Commit e3f3e8a

Browse files
committed
Improve performance of repeated same file import
1 parent 4296ec5 commit e3f3e8a

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

core/vm.cpp

+19-9
Original file line numberDiff line numberDiff line change
@@ -460,11 +460,16 @@ class Interpreter {
460460
struct ImportCacheValue {
461461
std::string foundHere;
462462
std::string content;
463+
/** Parsed desugared expression.
464+
*
465+
* Null if this file was only ever successfully imported with importstr.
466+
*/
467+
AST *expr;
463468
};
464469

465470
/** Cache for imported Jsonnet files. */
466471
std::map<std::pair<std::string, String>,
467-
const ImportCacheValue *> cachedImports;
472+
ImportCacheValue *> cachedImports;
468473

469474
/** External variables for std.extVar. */
470475
ExtMap externalVars;
@@ -688,12 +693,16 @@ class Interpreter {
688693
*/
689694
AST *import(const LocationRange &loc, const LiteralString *file)
690695
{
691-
const ImportCacheValue *input = importString(loc, file);
692-
Tokens tokens = jsonnet_lex(input->foundHere, input->content.c_str());
693-
AST *expr = jsonnet_parse(alloc, tokens);
694-
jsonnet_desugar(alloc, expr, nullptr);
695-
jsonnet_static_analysis(expr);
696-
return expr;
696+
ImportCacheValue *input = importString(loc, file);
697+
if (input->expr == nullptr) {
698+
Tokens tokens = jsonnet_lex(input->foundHere, input->content.c_str());
699+
AST *expr = jsonnet_parse(alloc, tokens);
700+
jsonnet_desugar(alloc, expr, nullptr);
701+
jsonnet_static_analysis(expr);
702+
// If no errors then populate cache.
703+
input->expr = expr;
704+
}
705+
return input->expr;
697706
}
698707

699708
/** Import a file as a string.
@@ -705,14 +714,14 @@ class Interpreter {
705714
* \param file Path to the filename.
706715
* \param found_here If non-null, used to store the actual path of the file
707716
*/
708-
const ImportCacheValue *importString(const LocationRange &loc, const LiteralString *file)
717+
ImportCacheValue *importString(const LocationRange &loc, const LiteralString *file)
709718
{
710719
std::string dir = dir_name(loc.file);
711720

712721
const String &path = file->value;
713722

714723
std::pair<std::string, String> key(dir, path);
715-
const ImportCacheValue *cached_value = cachedImports[key];
724+
ImportCacheValue *cached_value = cachedImports[key];
716725
if (cached_value != nullptr)
717726
return cached_value;
718727

@@ -734,6 +743,7 @@ class Interpreter {
734743
auto *input_ptr = new ImportCacheValue();
735744
input_ptr->foundHere = found_here_cptr;
736745
input_ptr->content = input;
746+
input_ptr->expr = nullptr; // May be filled in later by import().
737747
::free(found_here_cptr);
738748
cachedImports[key] = input_ptr;
739749
return input_ptr;

0 commit comments

Comments
 (0)