Data Imports in Optimizely: Part 4 - Only save when necessary

Saving to the Optimizely database is generally the most time consuming part of an import. The import can be sped up by saving as infrequently as possible.

The first time the import is run, it will be a worst case scenario as every item needs to be created in the database. However, subsequent runs where not all of the data is changing can be much faster.

The simplest option is to just check if a property is changing and only saving if it is different:

var needsSave = false;

if (page.Title != importedData.Title) {
    page.Title = importedData.Title;
    needsSave = true;
}

if (needsSave) {
    _contentRepository.Save(page, SaveAction.Publish | SaveAction.Patch, AccessLevel.NoAccess);
}

This can be tedious when there are dozens of properties to update. We can improve this by creating a function to perform this check for us.

private static void UpdateProperty<TPage, TProperty>(TPage page, string propertyName, TProperty newValue, ref bool needsSave) {
    var currentValue = page.Property[propertyName];
    
    if (currentValue != newValue) {
        page.Property[propertyName] = newValue;
        needsSave = true;
    }
}

// Update the import method
UpdateProperty(page, nameof(ImportedPage.Title), importedData.Title, ref needsSave);
Previous
Previous

Data Imports in Optimizely: Part 5 - Use async where possible

Next
Next

Data Imports in Optimizely: Part 3 - Query data efficiently