How to erase unsued space so that dumping userdata partition creates a sparse file of small size?
i guess your real purpose of this question is not what the headline suggests - secure erase your data - but instead you want to have a full backup of userdata including /data/media (downvote if i am wrong)  

you have some options, most require additional binaries which you can copy to /cache partition or permanently integrate into your twrp /sbin  


e2image (thx @IrfanLatif)
make twrp backup of /data to internal storage and just adb pull -a /sdcard afterwards, which you can zip without worry about file permissions  
just create tar.gz instead of img.gz with gnu tar (with --selinux --xattrs -p flags)  
create empty disk image and copy all (mke2fs + busybox cp -ac) then compress img with gz (requires much disk space and underlying non-fat32 file system type)  
permanent tweak for twrp  


(i will improve answer when i have time)