How do I reverse a String in Dart?

前端 未结 7 758
面向向阳花
面向向阳花 2021-02-03 20:13

I have a String, and I would like to reverse it. For example, I am writing an AngularDart filter that reverses a string. It\'s just for demonstration purposes, but it made me wo

7条回答
  •  情话喂你
    2021-02-03 20:54

    I've made a small benchmark for a few different alternatives:

    String reverse0(String s) {
      return s.split('').reversed.join('');
    }
    
    String reverse1(String s) {
      var sb = new StringBuffer();
      for(var i = s.length - 1; i >= 0; --i) {
        sb.write(s[i]);
      }
      return sb.toString();
    }
    
    String reverse2(String s) {
      return new String.fromCharCodes(s.codeUnits.reversed);
    }
    
    String reverse3(String s) {
      var sb = new StringBuffer();
      for(var i = s.length - 1; i >= 0; --i) {
        sb.writeCharCode(s.codeUnitAt(i));
      }
      return sb.toString();
    }
    
    String reverse4(String s) {
      var sb = new StringBuffer();
    
      var i = s.length - 1;
    
      while (i >= 3) {
        sb.writeCharCode(s.codeUnitAt(i-0));
        sb.writeCharCode(s.codeUnitAt(i-1));
        sb.writeCharCode(s.codeUnitAt(i-2));
        sb.writeCharCode(s.codeUnitAt(i-3));
        i -= 4;
      }
    
      while (i >= 0) {
        sb.writeCharCode(s.codeUnitAt(i));
        i -= 1;
      }
    
      return sb.toString();
    }
    
    String reverse5(String s) {
      var length = s.length;
      var charCodes = new List(length);
      for(var index = 0; index < length; index++) {
        charCodes[index] = s.codeUnitAt(length - index - 1);
      }
    
      return new String.fromCharCodes(charCodes);
    }
    main() {
      var s = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
    
      time('reverse0', () => reverse0(s));
      time('reverse1', () => reverse1(s));
      time('reverse2', () => reverse2(s));
      time('reverse3', () => reverse3(s));
      time('reverse4', () => reverse4(s));
      time('reverse5', () => reverse5(s));
    }
    

    Here is the result:

    reverse0: => 331,394 ops/sec (3 us) stdev(0.01363)
    reverse1: => 346,822 ops/sec (3 us) stdev(0.00885)
    reverse2: => 490,821 ops/sec (2 us) stdev(0.0338)
    reverse3: => 873,636 ops/sec (1 us) stdev(0.03972)
    reverse4: => 893,953 ops/sec (1 us) stdev(0.04089)
    reverse5: => 2,624,282 ops/sec (0 us) stdev(0.11828)
    

提交回复
热议问题