在realm.write()内部循环还是相反?

时间:2017-11-02 05:25:07

标签: react-native realm

我正在使用ES2015类架构模型:

<table *ngIf="receivedMessages?.length > 0;else noReceivedMessages" class="table table-responsive table-bordered animated bounceIn" style="table-layout: fixed;width:100%; word-wrap:break-word;">
                  <thead>
                    <tr>
                      <th></th>
                      <th>From</th>
                      <th>Date</th>
                      <th>Subject</th>
                      <th></th>
                      <th></th>


                    </tr>
                  </thead>
                  <tbody *ngFor="let message of receivedMessages">
                    <tr *ngIf="message.mDeleted == '0' ">
                      <td><i style="color:red" class="fa fa-exclamation" aria-hidden="true"></i></td>
                      <td> {{message.messageFrom}}</td>
                      <td> {{message.createdDate}}</td>
                      <td> {{message.subject}}</td>
                      <td><a style="width:100%;background-color:tomato;color:white" [routerLink]="['/message/'+message.$key]" href="" class="btn">
                        <i class="fa fa-arrow-circle-o-right"></i> Details</a></td>
                      <td> <button id="{{message.$key}}" *ngIf="message.readStatus == '0'" type="submit" class="btn btn-success" (click)="MarkasRead()">Mark as Read</button>
                      </td>
                    </tr>

                  </tbody>
                </table>






MarkasRead(){

      alert(this.id); // or alert($(this).attr('id'));

  }

假设我有很长的人员列表,每个人的项目都会循环更新。我发现在调试模式下,循环内的写入块比写入块内的循环更快。

更快:

class Person {
  get fullName() {
    return this.firstName + ' ' + this.lastName;
  }
}

Person.schema = {
  name: 'Person',
  properties: {
    firstName: 'string',
    lastName: 'string'
  }
};

慢:

componentDidMount(){
   realmWorker.addListener(()=>{
      console.log('from search screen');
   })
}

onClick=()=>{
   let persons = realm.objects('person');
   persons.forEach(person=>{
       realm.write(()=>{
          person.age++;
          // More complicated updates.
       })
   }) 
}

但我读到该文档更喜欢尽可能少的写入记录:

realm.write(()=>{

  let persons = realm.objects('person');
  persons.forEach(person=>{
      person.age++;
      // More complicated updates.
  }) 

})

那么我应该把整个循环放在写块中吗?

1 个答案:

答案 0 :(得分:2)

写事务是原子的,它是全部或全部。这意味着在事务中完成的更改应该是逻辑更改集。如果更改了两个对象,并且需要在这两个对象之间存在某种一致性,则应在一个事务中完成更改。如果更改是独立的,则可以(并且可能应该)在两个事务中完成更改。

以上是理论:-)我们在文档中写的是交易费用昂贵。原因是事务必须获取锁,并且必须将更改写入存储。

在调试RN应用程序时,更改仍会写入存储,但它们也会传送给调试器。这是一个缓慢的过程 - 例如参见https://github.com/realm/realm-js/issues/491。我最好的猜测是,由于app / debugger通信开销,许多小事务在调试时都很慢。在现实生活场景中(用户使用您的应用程序 - 没有调试器),循环外的写入事务将更快。