0

I have code to solve a sudoku board using a recursive algorithm.

The problem is that, when this code is run in Xcode, it solves the algorithm in 0.1 seconds, and when it is run in playgrounds, where I need it, it takes almost one minute.

When run in iPad, it takes about 30 seconds, but still obviously nowhere near the time it takes in xcode.

Any help or ideas would be appreciated, thank you.

  • 2
    Never measure performance in a Playground, since it doesn't represent real-world results due to compilation optimization differences. – Dávid Pásztor Mar 22 '19 at 16:24
  • I know, but for this project, I need it to be run in a playground. Is there anyway I could speed it up? –  Mar 22 '19 at 16:26
  • 1
    Yes. Don't use recursion. Or move the recursion out of the playground into Sources. – Rob Napier Mar 22 '19 at 16:30
  • Ok, I will add it to the sources –  Mar 22 '19 at 16:30
  • Every recursive algorithm can be converted into an iterative algorithm. that doesn't suggest brute force. – Rob Napier Mar 22 '19 at 16:31
  • @RobNapier why do you think that recursion slowdown playgrounds compared to iterative approach? – ManWithBear Mar 22 '19 at 16:35
  • @ManWithBear You make an excellent point. Playgrounds will likely cause the same problem due to printing. I said this because I was thinking about TCO in an optimized build (but I actually don't know that Swift does any TCO yet). – Rob Napier Mar 22 '19 at 16:37
  • 1
    @RobNapier https://stackoverflow.com/questions/24023580/does-swift-implement-tail-call-optimization-and-in-mutual-recursion-case – ManWithBear Mar 22 '19 at 16:40

1 Answers1

1
  1. Playground try to get result of each your operation and print it out (repl style)
  2. It just slow and laggy by itself
  3. In Xcode you can compile your code with additional optimization that speedup your code a lot (e. g. Swift Beta performance: sorting arrays)

Source files compiles as separate module, so don't forget about public/open access modifiers.
To create source files: enter image description here

ManWithBear
  • 2,787
  • 15
  • 27
  • I know, but I need this project to be done in playgrounds. Is there a way I can speed it up? –  Mar 22 '19 at 16:28
  • @NikolasIoannou you can try move all your logic code inside source files, then here will be less printings and it should be faster – ManWithBear Mar 22 '19 at 16:29
  • How can I create a source file? Thank you for helping! Do I just create a swift file in sources? –  Mar 22 '19 at 16:30
  • YES! That worked, thank you so much. I will accept it in 2 minutes when available. –  Mar 22 '19 at 16:33
  • @NikolasIoannou just for info, how fast it now? – ManWithBear Mar 22 '19 at 16:33