4

I'm working on a Hack project and I've come across a situation where I need to print $n spaces. Here's how I'm currently doing it:

for ($i = 0; $i < $n; $i++) echo " ";

I'm wondering whether $n calls to echo is the most efficient way to go about this? From a little bit of googling, I learned that generally, multiple calls to echo are faster than string concatenation and that Hack doesn't have a built in StringBuilder equivalent. Does my for loop achieve that maximum efficiency or is there something else I'm missing?

Thanks!

azjezz
  • 3,827
  • 1
  • 14
  • 35
Tom
  • 350
  • 4
  • 21
  • 4
    Use the proper tool https://www.php.net/manual/en/function.str-repeat.php or https://www.php.net/manual/en/function.str-pad.php – AbraCadaver May 22 '19 at 15:54

1 Answers1

4

If you are using HackLang, you should use HSL ( Hack standard library ) instead of legacy php functions.

The best way to go around this is to use Str\repeat function ( similar behavior as str_repeat in PHP )

use namespace HH\Lib\Str;

echo Str\repeat(' ', $n);

Note: make sure to use the same HSL version as HHVM

if you are using HHVM 4 ( recommended ), do composer require hhvm/hsl:^4

if you are using HHVM 3, do hhvm $(which composer) require hhvm/hsl:^3

etc...

azjezz
  • 3,827
  • 1
  • 14
  • 35