KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Convert collection to entity selection comparisons
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: July 10, 2019
Your current browser may not allow you to download the asset. We recommend Mozilla Firefox or Google Chrome.
Log In

One simple way to convert a collection of record objects to an entity selection is to use the dataClass.fromCollection(). However, using this member function will also write all of the entites into the dataClass which can be a large overhead in terms of execution time.

For example, converting 50,000 objects from a collection to an entity selection using dataClass.fromCollection will take roughly 7 seconds as shown in the code and execution time below.

C_COLLECTION($col_c)
$col_c:=ds.Contact.all().slice(0;50000).toCollection("")

C_LONGINT($start_l;$end_l;$duration_l)
C_OBJECT($sel_es)
$start_l:=Milliseconds
$sel_es:=ds.Contact.fromCollection($col_c)
$end_l:=Milliseconds
$duration_l:=$end_l-$start_l

ALERT("Execution time: "+String($duration_l)+"ms")




Another alternative to save execution time is to create a fresh new entity selection, loop through the collection, find each entity corresponding to the record object's primary key, and add that entity to the new entity selection as shown below. This way, there are no write operations which can greatly reduce overhead.

// ----------------------------------------------------
// Method: convertCollectionToEntSel
// Parameters:
// $1 - Table name
// $2 - Primary key field name
// $3 - Collection of record objects
// ----------------------------------------------------

C_TEXT($1;$tableName_t)
C_TEXT($2;$pkField_t)
C_COLLECTION($3;$col_c)
$tableName_t:=$1
$pkField_t:=$2
$col_c:=$3

C_OBJECT($dataClass)
$dataClass:=ds[$tableName_t]

C_LONGINT($start_l;$end_l;$duration_l)
$start_l:=Milliseconds

If ($dataClass#Null)
   C_OBJECT($sel_es;$all_es;$ent_o;$ent_e)
  
   $sel_es:=$dataClass.newSelection()
   $all_es:=$dataClass.all()
   For each ($ent_o;$col_c)
      $ent_e:=$all_es.query($pkField_t+" = :1";$ent_o[$pkField_t]).first()
      $sel_es.add($ent_e)
   End for each
Else
   ALERT("Table name \""+$tableName_t+"\" does not exist.")
End if

$end_l:=Milliseconds
$duration_l:=$end_l-$start_l
ALERT("Execution time: "+String($duration_l)+"ms")