navi-language / navi

Navi is a high-performance programming language.
https://navi-lang.org
94 stars 1 forks source link

Feature: StringBuilder / stringstream #9

Open KieranP opened 1 month ago

KieranP commented 1 month ago

A way to efficiently build strings. Current options include concatening string or building string array and calling join(''), neither of which is performant:

C#

var rendering = new StringBuilder();
for (var y = 0; y < height; y++) {
  for (var x = 0; x < width; x++) {
    var cell = cell_at(x, y);
    rendering.Append(cell.to_char());
  }
  rendering.Append("\n");
}
return rendering.ToString();

C++

stringstream rendering;
for (auto y = 0; y < height; y++) {
  for (auto x = 0; x < width; x++) {
    auto cell = *cell_at(x, y);
    rendering << cell->to_char();
  }
  rendering << "\n";
}
return rendering.str();

GoLang:

rendering := strings.Builder{}
rendering.Grow(world.width * world.height)
for y := range(world.height) {
    for x := range(world.width) {
        cell, _ := world.cell_at(x, y)
        rendering.WriteRune(cell.to_char())
    }
    rendering.WriteRune('\n')
}
return rendering.String()
sunli829 commented 1 month ago

For string concatenation, navi is optimized internally and does not need to copy the entire string, so StringBuilder is not needed.

KieranP commented 1 month ago

@sunli829 Ok, thank you. Is there a more efficient way to do this then?

    let rendering: [string] = [];
    for (let y in 0..self.height) {
      for (let x in 0..self.width) {
        let cell = self.cell_at(x, y);
        if (!cell.is_nil()) {
          rendering.push(cell!.to_char().to_string());
        }
      }
      rendering.push("\n");
    }
    return rendering.join("");

I have a Cell struct, with a to_char() method. It returns a char. But because there is no such thing as [Char].join() (it only works with [String].join(), I have to call to_string() on each char within the loop, which I think might be slowing things down? Any thoughts?

sunli829 commented 1 month ago

I will add [char].join() method