Skip to content
Fabian Morón Zirfas edited this page Jul 14, 2016 · 1 revision

Using loops to set a characterStyle or editing characters at all can take a long time. Using the functions like everyItem(), or itemByRange() that the InDesign API provides is way faster.
I wrote a test to compare those two approaches.

Using the loop takes 0.5 to 0.9 seconds Using the itemByRange takes between 0.006 and 0.04 seconds. (I can't tell why the range is so huge)

    function Timer() {
      var started = null;
      var stopped = null;
      this.start = function() {
        started = new Date();
      };
      this.stop = function() {
        stopped = new Date();
        var timetaken = (stopped.getTime() - started.getTime()) / 1000;
        return timetaken;
      };
    }
  
var useAPIfunctions = true;
var d = app.documents.add();
var p = d.pages[0];
p.textFrames.add({
    geometricBounds:[0,0, d.documentPreferences.pageHeight, d.documentPreferences.pageWidth]
  });
var s = d.stories[0];
var str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit,"+
" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis"+
" nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure"+
" dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur"+
" sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
var lastindex  = s.characters.length;
var cstyle = d.characterStyles.add({
    fillColor:d.swatches[5]
  });
// ------
if(useAPIfunctions === true){
// using IDAPI functions inner 
var duration1 = new Timer();
duration1.start();
s.insertionPoints.lastItem().contents = str;
var newlastindex =  s.characters.lastItem().index;
var txt = s.characters.itemByRange(lastindex + 1 ,newlastindex ).applyCharacterStyle(cstyle);
$.writeln("itemByRange took: " + duration1.stop());
//------
}else{
// using for loop  
var duration2 = new Timer();
duration2.start();
s.insertionPoints.lastItem().contents = str;
  for (var i = lastindex ; i < s.characters.length; i++) {
    s.characters[i].appliedCharacterStyle = cstyle;
  };
$.writeln("for loop took: " + duration2.stop());
}

Home

Clone this wiki locally