Question: I have an app that creates custom files that are shown in a gallery. They are not images or other standard media files. Because the files are large, I ask users for access to a folder in which the files will be stored.

So far so good.

Reading those files or file info via DocumentFile is so much slower than via File. Operations like

```
DocumentsContract.findDocumentPath()
documentFile.isFile()
documentFile.getName()

```

take up to 15ms each, which accumulates to a large time when reading a large number of files.

What's the best way to handle this? Is there another way to do this? I don't want the files to be in internal app memory or users might lose their work when they uninstall the app.

Thanks in advance! This is stressing me out a lot.

Answer: 
If you want to keep using recursion you have to use [memoization](https://en.wikipedia.org/wiki/Memoization), or caching. The idea is, when calculating a result, store it for later.

I suggest having an array of sufficient size, say 100 entries (seeing that the numbers grow just a bit slower than 2n, this should be enough to represent any 64-bit number). Initialize it to 0:

```
int test(int n)
{
    static int cache[100] = {0};
    ...
}

```

After calculating a result, store it in the correct index:

```
int test(int n)
{
    ...
    result = ...
    cache[n] = result;
    return result;
}

```

But before applying the formula, check if the cache contains the result:

```
int test(int n)
{
    ...
    if (cache[n] != 0)
        result = cache[n];
    ...
}

```
Time to get out the tail recursion hammer

```
static int testk(int i, int n, int a, int b, int c)
{
   if (i == n) return a + b + c;
   return testk(i + 1, n, a + b + c, a, b);
}

int test(int n) {
    if (n < 2) return n;
    return testk(3, n, 2, 1, 0);
}

```

This is a direct translation of anatolyg's answer to tail recursion.